Edit on GitHub

Expressions

Every AST node in SQLGlot is represented by a subclass of Expression.

This module contains the implementation of all supported Expression types. Additionally, it exposes a number of helper functions, which are mainly used to programmatically build SQL expressions, such as sqlglot.expressions.select.


   1"""
   2## Expressions
   3
   4Every AST node in SQLGlot is represented by a subclass of `Expression`.
   5
   6This module contains the implementation of all supported `Expression` types. Additionally,
   7it exposes a number of helper functions, which are mainly used to programmatically build
   8SQL expressions, such as `sqlglot.expressions.select`.
   9
  10----
  11"""
  12
  13from __future__ import annotations
  14
  15import datetime
  16import math
  17import numbers
  18import re
  19import typing as t
  20from collections import deque
  21from copy import deepcopy
  22from enum import auto
  23
  24from sqlglot._typing import E
  25from sqlglot.errors import ParseError
  26from sqlglot.helper import (
  27    AutoName,
  28    camel_to_snake_case,
  29    ensure_collection,
  30    ensure_list,
  31    seq_get,
  32    subclasses,
  33)
  34from sqlglot.tokens import Token
  35
  36if t.TYPE_CHECKING:
  37    from sqlglot.dialects.dialect import DialectType
  38
  39
  40class _Expression(type):
  41    def __new__(cls, clsname, bases, attrs):
  42        klass = super().__new__(cls, clsname, bases, attrs)
  43
  44        # When an Expression class is created, its key is automatically set to be
  45        # the lowercase version of the class' name.
  46        klass.key = clsname.lower()
  47
  48        # This is so that docstrings are not inherited in pdoc
  49        klass.__doc__ = klass.__doc__ or ""
  50
  51        return klass
  52
  53
  54class Expression(metaclass=_Expression):
  55    """
  56    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
  57    context, such as its child expressions, their names (arg keys), and whether a given child expression
  58    is optional or not.
  59
  60    Attributes:
  61        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
  62            and representing expressions as strings.
  63        arg_types: determines what arguments (child nodes) are supported by an expression. It
  64            maps arg keys to booleans that indicate whether the corresponding args are optional.
  65        parent: a reference to the parent expression (or None, in case of root expressions).
  66        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
  67            uses to refer to it.
  68        comments: a list of comments that are associated with a given expression. This is used in
  69            order to preserve comments when transpiling SQL code.
  70        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
  71            optimizer, in order to enable some transformations that require type information.
  72
  73    Example:
  74        >>> class Foo(Expression):
  75        ...     arg_types = {"this": True, "expression": False}
  76
  77        The above definition informs us that Foo is an Expression that requires an argument called
  78        "this" and may also optionally receive an argument called "expression".
  79
  80    Args:
  81        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
  82    """
  83
  84    key = "expression"
  85    arg_types = {"this": True}
  86    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
  87
  88    def __init__(self, **args: t.Any):
  89        self.args: t.Dict[str, t.Any] = args
  90        self.parent: t.Optional[Expression] = None
  91        self.arg_key: t.Optional[str] = None
  92        self.comments: t.Optional[t.List[str]] = None
  93        self._type: t.Optional[DataType] = None
  94        self._meta: t.Optional[t.Dict[str, t.Any]] = None
  95        self._hash: t.Optional[int] = None
  96
  97        for arg_key, value in self.args.items():
  98            self._set_parent(arg_key, value)
  99
 100    def __eq__(self, other) -> bool:
 101        return type(self) is type(other) and hash(self) == hash(other)
 102
 103    @property
 104    def hashable_args(self) -> t.Any:
 105        args = (self.args.get(k) for k in self.arg_types)
 106
 107        return tuple(
 108            (tuple(_norm_arg(a) for a in arg) if arg else None)
 109            if type(arg) is list
 110            else (_norm_arg(arg) if arg is not None and arg is not False else None)
 111            for arg in args
 112        )
 113
 114    def __hash__(self) -> int:
 115        if self._hash is not None:
 116            return self._hash
 117
 118        return hash((self.__class__, self.hashable_args))
 119
 120    @property
 121    def this(self):
 122        """
 123        Retrieves the argument with key "this".
 124        """
 125        return self.args.get("this")
 126
 127    @property
 128    def expression(self):
 129        """
 130        Retrieves the argument with key "expression".
 131        """
 132        return self.args.get("expression")
 133
 134    @property
 135    def expressions(self):
 136        """
 137        Retrieves the argument with key "expressions".
 138        """
 139        return self.args.get("expressions") or []
 140
 141    def text(self, key) -> str:
 142        """
 143        Returns a textual representation of the argument corresponding to "key". This can only be used
 144        for args that are strings or leaf Expression instances, such as identifiers and literals.
 145        """
 146        field = self.args.get(key)
 147        if isinstance(field, str):
 148            return field
 149        if isinstance(field, (Identifier, Literal, Var)):
 150            return field.this
 151        if isinstance(field, (Star, Null)):
 152            return field.name
 153        return ""
 154
 155    @property
 156    def is_string(self) -> bool:
 157        """
 158        Checks whether a Literal expression is a string.
 159        """
 160        return isinstance(self, Literal) and self.args["is_string"]
 161
 162    @property
 163    def is_number(self) -> bool:
 164        """
 165        Checks whether a Literal expression is a number.
 166        """
 167        return isinstance(self, Literal) and not self.args["is_string"]
 168
 169    @property
 170    def is_int(self) -> bool:
 171        """
 172        Checks whether a Literal expression is an integer.
 173        """
 174        if self.is_number:
 175            try:
 176                int(self.name)
 177                return True
 178            except ValueError:
 179                pass
 180        return False
 181
 182    @property
 183    def is_star(self) -> bool:
 184        """Checks whether an expression is a star."""
 185        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
 186
 187    @property
 188    def alias(self) -> str:
 189        """
 190        Returns the alias of the expression, or an empty string if it's not aliased.
 191        """
 192        if isinstance(self.args.get("alias"), TableAlias):
 193            return self.args["alias"].name
 194        return self.text("alias")
 195
 196    @property
 197    def name(self) -> str:
 198        return self.text("this")
 199
 200    @property
 201    def alias_or_name(self) -> str:
 202        return self.alias or self.name
 203
 204    @property
 205    def output_name(self) -> str:
 206        """
 207        Name of the output column if this expression is a selection.
 208
 209        If the Expression has no output name, an empty string is returned.
 210
 211        Example:
 212            >>> from sqlglot import parse_one
 213            >>> parse_one("SELECT a").expressions[0].output_name
 214            'a'
 215            >>> parse_one("SELECT b AS c").expressions[0].output_name
 216            'c'
 217            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
 218            ''
 219        """
 220        return ""
 221
 222    @property
 223    def type(self) -> t.Optional[DataType]:
 224        return self._type
 225
 226    @type.setter
 227    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
 228        if dtype and not isinstance(dtype, DataType):
 229            dtype = DataType.build(dtype)
 230        self._type = dtype  # type: ignore
 231
 232    @property
 233    def meta(self) -> t.Dict[str, t.Any]:
 234        if self._meta is None:
 235            self._meta = {}
 236        return self._meta
 237
 238    def __deepcopy__(self, memo):
 239        copy = self.__class__(**deepcopy(self.args))
 240        if self.comments is not None:
 241            copy.comments = deepcopy(self.comments)
 242
 243        if self._type is not None:
 244            copy._type = self._type.copy()
 245
 246        if self._meta is not None:
 247            copy._meta = deepcopy(self._meta)
 248
 249        return copy
 250
 251    def copy(self):
 252        """
 253        Returns a deep copy of the expression.
 254        """
 255        new = deepcopy(self)
 256        new.parent = self.parent
 257        return new
 258
 259    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
 260        if self.comments is None:
 261            self.comments = []
 262        if comments:
 263            self.comments.extend(comments)
 264
 265    def append(self, arg_key: str, value: t.Any) -> None:
 266        """
 267        Appends value to arg_key if it's a list or sets it as a new list.
 268
 269        Args:
 270            arg_key (str): name of the list expression arg
 271            value (Any): value to append to the list
 272        """
 273        if not isinstance(self.args.get(arg_key), list):
 274            self.args[arg_key] = []
 275        self.args[arg_key].append(value)
 276        self._set_parent(arg_key, value)
 277
 278    def set(self, arg_key: str, value: t.Any) -> None:
 279        """
 280        Sets `arg_key` to `value`.
 281
 282        Args:
 283            arg_key (str): name of the expression arg.
 284            value: value to set the arg to.
 285        """
 286        self.args[arg_key] = value
 287        self._set_parent(arg_key, value)
 288
 289    def _set_parent(self, arg_key: str, value: t.Any) -> None:
 290        if hasattr(value, "parent"):
 291            value.parent = self
 292            value.arg_key = arg_key
 293        elif type(value) is list:
 294            for v in value:
 295                if hasattr(v, "parent"):
 296                    v.parent = self
 297                    v.arg_key = arg_key
 298
 299    @property
 300    def depth(self) -> int:
 301        """
 302        Returns the depth of this tree.
 303        """
 304        if self.parent:
 305            return self.parent.depth + 1
 306        return 0
 307
 308    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
 309        """Yields the key and expression for all arguments, exploding list args."""
 310        for k, vs in self.args.items():
 311            if type(vs) is list:
 312                for v in vs:
 313                    if hasattr(v, "parent"):
 314                        yield k, v
 315            else:
 316                if hasattr(vs, "parent"):
 317                    yield k, vs
 318
 319    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
 320        """
 321        Returns the first node in this tree which matches at least one of
 322        the specified types.
 323
 324        Args:
 325            expression_types: the expression type(s) to match.
 326            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 327
 328        Returns:
 329            The node which matches the criteria or None if no such node was found.
 330        """
 331        return next(self.find_all(*expression_types, bfs=bfs), None)
 332
 333    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
 334        """
 335        Returns a generator object which visits all nodes in this tree and only
 336        yields those that match at least one of the specified expression types.
 337
 338        Args:
 339            expression_types: the expression type(s) to match.
 340            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
 341
 342        Returns:
 343            The generator object.
 344        """
 345        for expression, *_ in self.walk(bfs=bfs):
 346            if isinstance(expression, expression_types):
 347                yield expression
 348
 349    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
 350        """
 351        Returns a nearest parent matching expression_types.
 352
 353        Args:
 354            expression_types: the expression type(s) to match.
 355
 356        Returns:
 357            The parent node.
 358        """
 359        ancestor = self.parent
 360        while ancestor and not isinstance(ancestor, expression_types):
 361            ancestor = ancestor.parent
 362        return t.cast(E, ancestor)
 363
 364    @property
 365    def parent_select(self) -> t.Optional[Select]:
 366        """
 367        Returns the parent select statement.
 368        """
 369        return self.find_ancestor(Select)
 370
 371    @property
 372    def same_parent(self) -> bool:
 373        """Returns if the parent is the same class as itself."""
 374        return type(self.parent) is self.__class__
 375
 376    def root(self) -> Expression:
 377        """
 378        Returns the root expression of this tree.
 379        """
 380        expression = self
 381        while expression.parent:
 382            expression = expression.parent
 383        return expression
 384
 385    def walk(self, bfs=True, prune=None):
 386        """
 387        Returns a generator object which visits all nodes in this tree.
 388
 389        Args:
 390            bfs (bool): if set to True the BFS traversal order will be applied,
 391                otherwise the DFS traversal will be used instead.
 392            prune ((node, parent, arg_key) -> bool): callable that returns True if
 393                the generator should stop traversing this branch of the tree.
 394
 395        Returns:
 396            the generator object.
 397        """
 398        if bfs:
 399            yield from self.bfs(prune=prune)
 400        else:
 401            yield from self.dfs(prune=prune)
 402
 403    def dfs(self, parent=None, key=None, prune=None):
 404        """
 405        Returns a generator object which visits all nodes in this tree in
 406        the DFS (Depth-first) order.
 407
 408        Returns:
 409            The generator object.
 410        """
 411        parent = parent or self.parent
 412        yield self, parent, key
 413        if prune and prune(self, parent, key):
 414            return
 415
 416        for k, v in self.iter_expressions():
 417            yield from v.dfs(self, k, prune)
 418
 419    def bfs(self, prune=None):
 420        """
 421        Returns a generator object which visits all nodes in this tree in
 422        the BFS (Breadth-first) order.
 423
 424        Returns:
 425            The generator object.
 426        """
 427        queue = deque([(self, self.parent, None)])
 428
 429        while queue:
 430            item, parent, key = queue.popleft()
 431
 432            yield item, parent, key
 433            if prune and prune(item, parent, key):
 434                continue
 435
 436            for k, v in item.iter_expressions():
 437                queue.append((v, item, k))
 438
 439    def unnest(self):
 440        """
 441        Returns the first non parenthesis child or self.
 442        """
 443        expression = self
 444        while type(expression) is Paren:
 445            expression = expression.this
 446        return expression
 447
 448    def unalias(self):
 449        """
 450        Returns the inner expression if this is an Alias.
 451        """
 452        if isinstance(self, Alias):
 453            return self.this
 454        return self
 455
 456    def unnest_operands(self):
 457        """
 458        Returns unnested operands as a tuple.
 459        """
 460        return tuple(arg.unnest() for _, arg in self.iter_expressions())
 461
 462    def flatten(self, unnest=True):
 463        """
 464        Returns a generator which yields child nodes who's parents are the same class.
 465
 466        A AND B AND C -> [A, B, C]
 467        """
 468        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
 469            if not type(node) is self.__class__:
 470                yield node.unnest() if unnest else node
 471
 472    def __str__(self) -> str:
 473        return self.sql()
 474
 475    def __repr__(self) -> str:
 476        return self._to_s()
 477
 478    def sql(self, dialect: DialectType = None, **opts) -> str:
 479        """
 480        Returns SQL string representation of this tree.
 481
 482        Args:
 483            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
 484            opts: other `sqlglot.generator.Generator` options.
 485
 486        Returns:
 487            The SQL string.
 488        """
 489        from sqlglot.dialects import Dialect
 490
 491        return Dialect.get_or_raise(dialect)().generate(self, **opts)
 492
 493    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
 494        indent = "" if not level else "\n"
 495        indent += "".join(["  "] * level)
 496        left = f"({self.key.upper()} "
 497
 498        args: t.Dict[str, t.Any] = {
 499            k: ", ".join(
 500                v._to_s(hide_missing=hide_missing, level=level + 1)
 501                if hasattr(v, "_to_s")
 502                else str(v)
 503                for v in ensure_list(vs)
 504                if v is not None
 505            )
 506            for k, vs in self.args.items()
 507        }
 508        args["comments"] = self.comments
 509        args["type"] = self.type
 510        args = {k: v for k, v in args.items() if v or not hide_missing}
 511
 512        right = ", ".join(f"{k}: {v}" for k, v in args.items())
 513        right += ")"
 514
 515        return indent + left + right
 516
 517    def transform(self, fun, *args, copy=True, **kwargs):
 518        """
 519        Recursively visits all tree nodes (excluding already transformed ones)
 520        and applies the given transformation function to each node.
 521
 522        Args:
 523            fun (function): a function which takes a node as an argument and returns a
 524                new transformed node or the same node without modifications. If the function
 525                returns None, then the corresponding node will be removed from the syntax tree.
 526            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
 527                modified in place.
 528
 529        Returns:
 530            The transformed tree.
 531        """
 532        node = self.copy() if copy else self
 533        new_node = fun(node, *args, **kwargs)
 534
 535        if new_node is None or not isinstance(new_node, Expression):
 536            return new_node
 537        if new_node is not node:
 538            new_node.parent = node.parent
 539            return new_node
 540
 541        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
 542        return new_node
 543
 544    @t.overload
 545    def replace(self, expression: E) -> E:
 546        ...
 547
 548    @t.overload
 549    def replace(self, expression: None) -> None:
 550        ...
 551
 552    def replace(self, expression):
 553        """
 554        Swap out this expression with a new expression.
 555
 556        For example::
 557
 558            >>> tree = Select().select("x").from_("tbl")
 559            >>> tree.find(Column).replace(Column(this="y"))
 560            (COLUMN this: y)
 561            >>> tree.sql()
 562            'SELECT y FROM tbl'
 563
 564        Args:
 565            expression: new node
 566
 567        Returns:
 568            The new expression or expressions.
 569        """
 570        if not self.parent:
 571            return expression
 572
 573        parent = self.parent
 574        self.parent = None
 575
 576        replace_children(parent, lambda child: expression if child is self else child)
 577        return expression
 578
 579    def pop(self: E) -> E:
 580        """
 581        Remove this expression from its AST.
 582
 583        Returns:
 584            The popped expression.
 585        """
 586        self.replace(None)
 587        return self
 588
 589    def assert_is(self, type_: t.Type[E]) -> E:
 590        """
 591        Assert that this `Expression` is an instance of `type_`.
 592
 593        If it is NOT an instance of `type_`, this raises an assertion error.
 594        Otherwise, this returns this expression.
 595
 596        Examples:
 597            This is useful for type security in chained expressions:
 598
 599            >>> import sqlglot
 600            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
 601            'SELECT x, z FROM y'
 602        """
 603        assert isinstance(self, type_)
 604        return self
 605
 606    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
 607        """
 608        Checks if this expression is valid (e.g. all mandatory args are set).
 609
 610        Args:
 611            args: a sequence of values that were used to instantiate a Func expression. This is used
 612                to check that the provided arguments don't exceed the function argument limit.
 613
 614        Returns:
 615            A list of error messages for all possible errors that were found.
 616        """
 617        errors: t.List[str] = []
 618
 619        for k in self.args:
 620            if k not in self.arg_types:
 621                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
 622        for k, mandatory in self.arg_types.items():
 623            v = self.args.get(k)
 624            if mandatory and (v is None or (isinstance(v, list) and not v)):
 625                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
 626
 627        if (
 628            args
 629            and isinstance(self, Func)
 630            and len(args) > len(self.arg_types)
 631            and not self.is_var_len_args
 632        ):
 633            errors.append(
 634                f"The number of provided arguments ({len(args)}) is greater than "
 635                f"the maximum number of supported arguments ({len(self.arg_types)})"
 636            )
 637
 638        return errors
 639
 640    def dump(self):
 641        """
 642        Dump this Expression to a JSON-serializable dict.
 643        """
 644        from sqlglot.serde import dump
 645
 646        return dump(self)
 647
 648    @classmethod
 649    def load(cls, obj):
 650        """
 651        Load a dict (as returned by `Expression.dump`) into an Expression instance.
 652        """
 653        from sqlglot.serde import load
 654
 655        return load(obj)
 656
 657
 658IntoType = t.Union[
 659    str,
 660    t.Type[Expression],
 661    t.Collection[t.Union[str, t.Type[Expression]]],
 662]
 663ExpOrStr = t.Union[str, Expression]
 664
 665
 666class Condition(Expression):
 667    def and_(
 668        self,
 669        *expressions: t.Optional[ExpOrStr],
 670        dialect: DialectType = None,
 671        copy: bool = True,
 672        **opts,
 673    ) -> Condition:
 674        """
 675        AND this condition with one or multiple expressions.
 676
 677        Example:
 678            >>> condition("x=1").and_("y=1").sql()
 679            'x = 1 AND y = 1'
 680
 681        Args:
 682            *expressions: the SQL code strings to parse.
 683                If an `Expression` instance is passed, it will be used as-is.
 684            dialect: the dialect used to parse the input expression.
 685            copy: whether or not to copy the involved expressions (only applies to Expressions).
 686            opts: other options to use to parse the input expressions.
 687
 688        Returns:
 689            The new And condition.
 690        """
 691        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
 692
 693    def or_(
 694        self,
 695        *expressions: t.Optional[ExpOrStr],
 696        dialect: DialectType = None,
 697        copy: bool = True,
 698        **opts,
 699    ) -> Condition:
 700        """
 701        OR this condition with one or multiple expressions.
 702
 703        Example:
 704            >>> condition("x=1").or_("y=1").sql()
 705            'x = 1 OR y = 1'
 706
 707        Args:
 708            *expressions: the SQL code strings to parse.
 709                If an `Expression` instance is passed, it will be used as-is.
 710            dialect: the dialect used to parse the input expression.
 711            copy: whether or not to copy the involved expressions (only applies to Expressions).
 712            opts: other options to use to parse the input expressions.
 713
 714        Returns:
 715            The new Or condition.
 716        """
 717        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
 718
 719    def not_(self, copy: bool = True):
 720        """
 721        Wrap this condition with NOT.
 722
 723        Example:
 724            >>> condition("x=1").not_().sql()
 725            'NOT x = 1'
 726
 727        Args:
 728            copy: whether or not to copy this object.
 729
 730        Returns:
 731            The new Not instance.
 732        """
 733        return not_(self, copy=copy)
 734
 735    def as_(
 736        self,
 737        alias: str | Identifier,
 738        quoted: t.Optional[bool] = None,
 739        dialect: DialectType = None,
 740        copy: bool = True,
 741        **opts,
 742    ) -> Alias:
 743        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
 744
 745    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
 746        this = self.copy()
 747        other = convert(other, copy=True)
 748        if not isinstance(this, klass) and not isinstance(other, klass):
 749            this = _wrap(this, Binary)
 750            other = _wrap(other, Binary)
 751        if reverse:
 752            return klass(this=other, expression=this)
 753        return klass(this=this, expression=other)
 754
 755    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
 756        return Bracket(
 757            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
 758        )
 759
 760    def isin(
 761        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
 762    ) -> In:
 763        return In(
 764            this=_maybe_copy(self, copy),
 765            expressions=[convert(e, copy=copy) for e in expressions],
 766            query=maybe_parse(query, copy=copy, **opts) if query else None,
 767        )
 768
 769    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
 770        return Between(
 771            this=_maybe_copy(self, copy),
 772            low=convert(low, copy=copy, **opts),
 773            high=convert(high, copy=copy, **opts),
 774        )
 775
 776    def is_(self, other: ExpOrStr) -> Is:
 777        return self._binop(Is, other)
 778
 779    def like(self, other: ExpOrStr) -> Like:
 780        return self._binop(Like, other)
 781
 782    def ilike(self, other: ExpOrStr) -> ILike:
 783        return self._binop(ILike, other)
 784
 785    def eq(self, other: t.Any) -> EQ:
 786        return self._binop(EQ, other)
 787
 788    def neq(self, other: t.Any) -> NEQ:
 789        return self._binop(NEQ, other)
 790
 791    def rlike(self, other: ExpOrStr) -> RegexpLike:
 792        return self._binop(RegexpLike, other)
 793
 794    def __lt__(self, other: t.Any) -> LT:
 795        return self._binop(LT, other)
 796
 797    def __le__(self, other: t.Any) -> LTE:
 798        return self._binop(LTE, other)
 799
 800    def __gt__(self, other: t.Any) -> GT:
 801        return self._binop(GT, other)
 802
 803    def __ge__(self, other: t.Any) -> GTE:
 804        return self._binop(GTE, other)
 805
 806    def __add__(self, other: t.Any) -> Add:
 807        return self._binop(Add, other)
 808
 809    def __radd__(self, other: t.Any) -> Add:
 810        return self._binop(Add, other, reverse=True)
 811
 812    def __sub__(self, other: t.Any) -> Sub:
 813        return self._binop(Sub, other)
 814
 815    def __rsub__(self, other: t.Any) -> Sub:
 816        return self._binop(Sub, other, reverse=True)
 817
 818    def __mul__(self, other: t.Any) -> Mul:
 819        return self._binop(Mul, other)
 820
 821    def __rmul__(self, other: t.Any) -> Mul:
 822        return self._binop(Mul, other, reverse=True)
 823
 824    def __truediv__(self, other: t.Any) -> Div:
 825        return self._binop(Div, other)
 826
 827    def __rtruediv__(self, other: t.Any) -> Div:
 828        return self._binop(Div, other, reverse=True)
 829
 830    def __floordiv__(self, other: t.Any) -> IntDiv:
 831        return self._binop(IntDiv, other)
 832
 833    def __rfloordiv__(self, other: t.Any) -> IntDiv:
 834        return self._binop(IntDiv, other, reverse=True)
 835
 836    def __mod__(self, other: t.Any) -> Mod:
 837        return self._binop(Mod, other)
 838
 839    def __rmod__(self, other: t.Any) -> Mod:
 840        return self._binop(Mod, other, reverse=True)
 841
 842    def __pow__(self, other: t.Any) -> Pow:
 843        return self._binop(Pow, other)
 844
 845    def __rpow__(self, other: t.Any) -> Pow:
 846        return self._binop(Pow, other, reverse=True)
 847
 848    def __and__(self, other: t.Any) -> And:
 849        return self._binop(And, other)
 850
 851    def __rand__(self, other: t.Any) -> And:
 852        return self._binop(And, other, reverse=True)
 853
 854    def __or__(self, other: t.Any) -> Or:
 855        return self._binop(Or, other)
 856
 857    def __ror__(self, other: t.Any) -> Or:
 858        return self._binop(Or, other, reverse=True)
 859
 860    def __neg__(self) -> Neg:
 861        return Neg(this=_wrap(self.copy(), Binary))
 862
 863    def __invert__(self) -> Not:
 864        return not_(self.copy())
 865
 866
 867class Predicate(Condition):
 868    """Relationships like x = y, x > 1, x >= y."""
 869
 870
 871class DerivedTable(Expression):
 872    @property
 873    def alias_column_names(self) -> t.List[str]:
 874        table_alias = self.args.get("alias")
 875        if not table_alias:
 876            return []
 877        return [c.name for c in table_alias.args.get("columns") or []]
 878
 879    @property
 880    def selects(self):
 881        return self.this.selects if isinstance(self.this, Subqueryable) else []
 882
 883    @property
 884    def named_selects(self):
 885        return [select.output_name for select in self.selects]
 886
 887
 888class Unionable(Expression):
 889    def union(
 890        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 891    ) -> Unionable:
 892        """
 893        Builds a UNION expression.
 894
 895        Example:
 896            >>> import sqlglot
 897            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
 898            'SELECT * FROM foo UNION SELECT * FROM bla'
 899
 900        Args:
 901            expression: the SQL code string.
 902                If an `Expression` instance is passed, it will be used as-is.
 903            distinct: set the DISTINCT flag if and only if this is true.
 904            dialect: the dialect used to parse the input expression.
 905            opts: other options to use to parse the input expressions.
 906
 907        Returns:
 908            The new Union expression.
 909        """
 910        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 911
 912    def intersect(
 913        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 914    ) -> Unionable:
 915        """
 916        Builds an INTERSECT expression.
 917
 918        Example:
 919            >>> import sqlglot
 920            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
 921            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
 922
 923        Args:
 924            expression: the SQL code string.
 925                If an `Expression` instance is passed, it will be used as-is.
 926            distinct: set the DISTINCT flag if and only if this is true.
 927            dialect: the dialect used to parse the input expression.
 928            opts: other options to use to parse the input expressions.
 929
 930        Returns:
 931            The new Intersect expression.
 932        """
 933        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 934
 935    def except_(
 936        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
 937    ) -> Unionable:
 938        """
 939        Builds an EXCEPT expression.
 940
 941        Example:
 942            >>> import sqlglot
 943            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
 944            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
 945
 946        Args:
 947            expression: the SQL code string.
 948                If an `Expression` instance is passed, it will be used as-is.
 949            distinct: set the DISTINCT flag if and only if this is true.
 950            dialect: the dialect used to parse the input expression.
 951            opts: other options to use to parse the input expressions.
 952
 953        Returns:
 954            The new Except expression.
 955        """
 956        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
 957
 958
 959class UDTF(DerivedTable, Unionable):
 960    @property
 961    def selects(self):
 962        alias = self.args.get("alias")
 963        return alias.columns if alias else []
 964
 965
 966class Cache(Expression):
 967    arg_types = {
 968        "with": False,
 969        "this": True,
 970        "lazy": False,
 971        "options": False,
 972        "expression": False,
 973    }
 974
 975
 976class Uncache(Expression):
 977    arg_types = {"this": True, "exists": False}
 978
 979
 980class Create(Expression):
 981    arg_types = {
 982        "with": False,
 983        "this": True,
 984        "kind": True,
 985        "expression": False,
 986        "exists": False,
 987        "properties": False,
 988        "replace": False,
 989        "unique": False,
 990        "indexes": False,
 991        "no_schema_binding": False,
 992        "begin": False,
 993        "clone": False,
 994    }
 995
 996
 997# https://docs.snowflake.com/en/sql-reference/sql/create-clone
 998class Clone(Expression):
 999    arg_types = {
1000        "this": True,
1001        "when": False,
1002        "kind": False,
1003        "expression": False,
1004    }
1005
1006
1007class Describe(Expression):
1008    arg_types = {"this": True, "kind": False}
1009
1010
1011class Pragma(Expression):
1012    pass
1013
1014
1015class Set(Expression):
1016    arg_types = {"expressions": False}
1017
1018
1019class SetItem(Expression):
1020    arg_types = {
1021        "this": False,
1022        "expressions": False,
1023        "kind": False,
1024        "collate": False,  # MySQL SET NAMES statement
1025        "global": False,
1026    }
1027
1028
1029class Show(Expression):
1030    arg_types = {
1031        "this": True,
1032        "target": False,
1033        "offset": False,
1034        "limit": False,
1035        "like": False,
1036        "where": False,
1037        "db": False,
1038        "full": False,
1039        "mutex": False,
1040        "query": False,
1041        "channel": False,
1042        "global": False,
1043        "log": False,
1044        "position": False,
1045        "types": False,
1046    }
1047
1048
1049class UserDefinedFunction(Expression):
1050    arg_types = {"this": True, "expressions": False, "wrapped": False}
1051
1052
1053class CharacterSet(Expression):
1054    arg_types = {"this": True, "default": False}
1055
1056
1057class With(Expression):
1058    arg_types = {"expressions": True, "recursive": False}
1059
1060    @property
1061    def recursive(self) -> bool:
1062        return bool(self.args.get("recursive"))
1063
1064
1065class WithinGroup(Expression):
1066    arg_types = {"this": True, "expression": False}
1067
1068
1069class CTE(DerivedTable):
1070    arg_types = {"this": True, "alias": True}
1071
1072
1073class TableAlias(Expression):
1074    arg_types = {"this": False, "columns": False}
1075
1076    @property
1077    def columns(self):
1078        return self.args.get("columns") or []
1079
1080
1081class BitString(Condition):
1082    pass
1083
1084
1085class HexString(Condition):
1086    pass
1087
1088
1089class ByteString(Condition):
1090    pass
1091
1092
1093class RawString(Condition):
1094    pass
1095
1096
1097class Column(Condition):
1098    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1099
1100    @property
1101    def table(self) -> str:
1102        return self.text("table")
1103
1104    @property
1105    def db(self) -> str:
1106        return self.text("db")
1107
1108    @property
1109    def catalog(self) -> str:
1110        return self.text("catalog")
1111
1112    @property
1113    def output_name(self) -> str:
1114        return self.name
1115
1116    @property
1117    def parts(self) -> t.List[Identifier]:
1118        """Return the parts of a column in order catalog, db, table, name."""
1119        return [
1120            t.cast(Identifier, self.args[part])
1121            for part in ("catalog", "db", "table", "this")
1122            if self.args.get(part)
1123        ]
1124
1125    def to_dot(self) -> Dot:
1126        """Converts the column into a dot expression."""
1127        parts = self.parts
1128        parent = self.parent
1129
1130        while parent:
1131            if isinstance(parent, Dot):
1132                parts.append(parent.expression)
1133            parent = parent.parent
1134
1135        return Dot.build(parts)
1136
1137
1138class ColumnPosition(Expression):
1139    arg_types = {"this": False, "position": True}
1140
1141
1142class ColumnDef(Expression):
1143    arg_types = {
1144        "this": True,
1145        "kind": False,
1146        "constraints": False,
1147        "exists": False,
1148        "position": False,
1149    }
1150
1151    @property
1152    def constraints(self) -> t.List[ColumnConstraint]:
1153        return self.args.get("constraints") or []
1154
1155
1156class AlterColumn(Expression):
1157    arg_types = {
1158        "this": True,
1159        "dtype": False,
1160        "collate": False,
1161        "using": False,
1162        "default": False,
1163        "drop": False,
1164    }
1165
1166
1167class RenameTable(Expression):
1168    pass
1169
1170
1171class SetTag(Expression):
1172    arg_types = {"expressions": True, "unset": False}
1173
1174
1175class Comment(Expression):
1176    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
1177
1178
1179# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1180class MergeTreeTTLAction(Expression):
1181    arg_types = {
1182        "this": True,
1183        "delete": False,
1184        "recompress": False,
1185        "to_disk": False,
1186        "to_volume": False,
1187    }
1188
1189
1190# https://clickhouse.com/docs/en/engines/table-engines/mergetree-family/mergetree#mergetree-table-ttl
1191class MergeTreeTTL(Expression):
1192    arg_types = {
1193        "expressions": True,
1194        "where": False,
1195        "group": False,
1196        "aggregates": False,
1197    }
1198
1199
1200class ColumnConstraint(Expression):
1201    arg_types = {"this": False, "kind": True}
1202
1203    @property
1204    def kind(self) -> ColumnConstraintKind:
1205        return self.args["kind"]
1206
1207
1208class ColumnConstraintKind(Expression):
1209    pass
1210
1211
1212class AutoIncrementColumnConstraint(ColumnConstraintKind):
1213    pass
1214
1215
1216class CaseSpecificColumnConstraint(ColumnConstraintKind):
1217    arg_types = {"not_": True}
1218
1219
1220class CharacterSetColumnConstraint(ColumnConstraintKind):
1221    arg_types = {"this": True}
1222
1223
1224class CheckColumnConstraint(ColumnConstraintKind):
1225    pass
1226
1227
1228class CollateColumnConstraint(ColumnConstraintKind):
1229    pass
1230
1231
1232class CommentColumnConstraint(ColumnConstraintKind):
1233    pass
1234
1235
1236class CompressColumnConstraint(ColumnConstraintKind):
1237    pass
1238
1239
1240class DateFormatColumnConstraint(ColumnConstraintKind):
1241    arg_types = {"this": True}
1242
1243
1244class DefaultColumnConstraint(ColumnConstraintKind):
1245    pass
1246
1247
1248class EncodeColumnConstraint(ColumnConstraintKind):
1249    pass
1250
1251
1252class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1253    # this: True -> ALWAYS, this: False -> BY DEFAULT
1254    arg_types = {
1255        "this": False,
1256        "expression": False,
1257        "on_null": False,
1258        "start": False,
1259        "increment": False,
1260        "minvalue": False,
1261        "maxvalue": False,
1262        "cycle": False,
1263    }
1264
1265
1266class InlineLengthColumnConstraint(ColumnConstraintKind):
1267    pass
1268
1269
1270class NotNullColumnConstraint(ColumnConstraintKind):
1271    arg_types = {"allow_null": False}
1272
1273
1274# https://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
1275class OnUpdateColumnConstraint(ColumnConstraintKind):
1276    pass
1277
1278
1279class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1280    arg_types = {"desc": False}
1281
1282
1283class TitleColumnConstraint(ColumnConstraintKind):
1284    pass
1285
1286
1287class UniqueColumnConstraint(ColumnConstraintKind):
1288    arg_types = {"this": False}
1289
1290
1291class UppercaseColumnConstraint(ColumnConstraintKind):
1292    arg_types: t.Dict[str, t.Any] = {}
1293
1294
1295class PathColumnConstraint(ColumnConstraintKind):
1296    pass
1297
1298
1299class Constraint(Expression):
1300    arg_types = {"this": True, "expressions": True}
1301
1302
1303class Delete(Expression):
1304    arg_types = {
1305        "with": False,
1306        "this": False,
1307        "using": False,
1308        "where": False,
1309        "returning": False,
1310        "limit": False,
1311    }
1312
1313    def delete(
1314        self,
1315        table: ExpOrStr,
1316        dialect: DialectType = None,
1317        copy: bool = True,
1318        **opts,
1319    ) -> Delete:
1320        """
1321        Create a DELETE expression or replace the table on an existing DELETE expression.
1322
1323        Example:
1324            >>> delete("tbl").sql()
1325            'DELETE FROM tbl'
1326
1327        Args:
1328            table: the table from which to delete.
1329            dialect: the dialect used to parse the input expression.
1330            copy: if `False`, modify this expression instance in-place.
1331            opts: other options to use to parse the input expressions.
1332
1333        Returns:
1334            Delete: the modified expression.
1335        """
1336        return _apply_builder(
1337            expression=table,
1338            instance=self,
1339            arg="this",
1340            dialect=dialect,
1341            into=Table,
1342            copy=copy,
1343            **opts,
1344        )
1345
1346    def where(
1347        self,
1348        *expressions: t.Optional[ExpOrStr],
1349        append: bool = True,
1350        dialect: DialectType = None,
1351        copy: bool = True,
1352        **opts,
1353    ) -> Delete:
1354        """
1355        Append to or set the WHERE expressions.
1356
1357        Example:
1358            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1359            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1360
1361        Args:
1362            *expressions: the SQL code strings to parse.
1363                If an `Expression` instance is passed, it will be used as-is.
1364                Multiple expressions are combined with an AND operator.
1365            append: if `True`, AND the new expressions to any existing expression.
1366                Otherwise, this resets the expression.
1367            dialect: the dialect used to parse the input expressions.
1368            copy: if `False`, modify this expression instance in-place.
1369            opts: other options to use to parse the input expressions.
1370
1371        Returns:
1372            Delete: the modified expression.
1373        """
1374        return _apply_conjunction_builder(
1375            *expressions,
1376            instance=self,
1377            arg="where",
1378            append=append,
1379            into=Where,
1380            dialect=dialect,
1381            copy=copy,
1382            **opts,
1383        )
1384
1385    def returning(
1386        self,
1387        expression: ExpOrStr,
1388        dialect: DialectType = None,
1389        copy: bool = True,
1390        **opts,
1391    ) -> Delete:
1392        """
1393        Set the RETURNING expression. Not supported by all dialects.
1394
1395        Example:
1396            >>> delete("tbl").returning("*", dialect="postgres").sql()
1397            'DELETE FROM tbl RETURNING *'
1398
1399        Args:
1400            expression: the SQL code strings to parse.
1401                If an `Expression` instance is passed, it will be used as-is.
1402            dialect: the dialect used to parse the input expressions.
1403            copy: if `False`, modify this expression instance in-place.
1404            opts: other options to use to parse the input expressions.
1405
1406        Returns:
1407            Delete: the modified expression.
1408        """
1409        return _apply_builder(
1410            expression=expression,
1411            instance=self,
1412            arg="returning",
1413            prefix="RETURNING",
1414            dialect=dialect,
1415            copy=copy,
1416            into=Returning,
1417            **opts,
1418        )
1419
1420
1421class Drop(Expression):
1422    arg_types = {
1423        "this": False,
1424        "kind": False,
1425        "exists": False,
1426        "temporary": False,
1427        "materialized": False,
1428        "cascade": False,
1429        "constraints": False,
1430        "purge": False,
1431    }
1432
1433
1434class Filter(Expression):
1435    arg_types = {"this": True, "expression": True}
1436
1437
1438class Check(Expression):
1439    pass
1440
1441
1442class Directory(Expression):
1443    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1444    arg_types = {"this": True, "local": False, "row_format": False}
1445
1446
1447class ForeignKey(Expression):
1448    arg_types = {
1449        "expressions": True,
1450        "reference": False,
1451        "delete": False,
1452        "update": False,
1453    }
1454
1455
1456class PrimaryKey(Expression):
1457    arg_types = {"expressions": True, "options": False}
1458
1459
1460# https://www.postgresql.org/docs/9.1/sql-selectinto.html
1461# https://docs.aws.amazon.com/redshift/latest/dg/r_SELECT_INTO.html#r_SELECT_INTO-examples
1462class Into(Expression):
1463    arg_types = {"this": True, "temporary": False, "unlogged": False}
1464
1465
1466class From(Expression):
1467    @property
1468    def name(self) -> str:
1469        return self.this.name
1470
1471    @property
1472    def alias_or_name(self) -> str:
1473        return self.this.alias_or_name
1474
1475
1476class Having(Expression):
1477    pass
1478
1479
1480class Hint(Expression):
1481    arg_types = {"expressions": True}
1482
1483
1484class JoinHint(Expression):
1485    arg_types = {"this": True, "expressions": True}
1486
1487
1488class Identifier(Expression):
1489    arg_types = {"this": True, "quoted": False}
1490
1491    @property
1492    def quoted(self) -> bool:
1493        return bool(self.args.get("quoted"))
1494
1495    @property
1496    def hashable_args(self) -> t.Any:
1497        if self.quoted and any(char.isupper() for char in self.this):
1498            return (self.this, self.quoted)
1499        return self.this.lower()
1500
1501    @property
1502    def output_name(self) -> str:
1503        return self.name
1504
1505
1506class Index(Expression):
1507    arg_types = {
1508        "this": False,
1509        "table": False,
1510        "using": False,
1511        "where": False,
1512        "columns": False,
1513        "unique": False,
1514        "primary": False,
1515        "amp": False,  # teradata
1516        "partition_by": False,  # teradata
1517    }
1518
1519
1520class Insert(Expression):
1521    arg_types = {
1522        "with": False,
1523        "this": True,
1524        "expression": False,
1525        "conflict": False,
1526        "returning": False,
1527        "overwrite": False,
1528        "exists": False,
1529        "partition": False,
1530        "alternative": False,
1531    }
1532
1533    def with_(
1534        self,
1535        alias: ExpOrStr,
1536        as_: ExpOrStr,
1537        recursive: t.Optional[bool] = None,
1538        append: bool = True,
1539        dialect: DialectType = None,
1540        copy: bool = True,
1541        **opts,
1542    ) -> Insert:
1543        """
1544        Append to or set the common table expressions.
1545
1546        Example:
1547            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1548            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1549
1550        Args:
1551            alias: the SQL code string to parse as the table name.
1552                If an `Expression` instance is passed, this is used as-is.
1553            as_: the SQL code string to parse as the table expression.
1554                If an `Expression` instance is passed, it will be used as-is.
1555            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1556            append: if `True`, add to any existing expressions.
1557                Otherwise, this resets the expressions.
1558            dialect: the dialect used to parse the input expression.
1559            copy: if `False`, modify this expression instance in-place.
1560            opts: other options to use to parse the input expressions.
1561
1562        Returns:
1563            The modified expression.
1564        """
1565        return _apply_cte_builder(
1566            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1567        )
1568
1569
1570class OnConflict(Expression):
1571    arg_types = {
1572        "duplicate": False,
1573        "expressions": False,
1574        "nothing": False,
1575        "key": False,
1576        "constraint": False,
1577    }
1578
1579
1580class Returning(Expression):
1581    arg_types = {"expressions": True}
1582
1583
1584# https://dev.mysql.com/doc/refman/8.0/en/charset-introducer.html
1585class Introducer(Expression):
1586    arg_types = {"this": True, "expression": True}
1587
1588
1589# national char, like n'utf8'
1590class National(Expression):
1591    pass
1592
1593
1594class LoadData(Expression):
1595    arg_types = {
1596        "this": True,
1597        "local": False,
1598        "overwrite": False,
1599        "inpath": True,
1600        "partition": False,
1601        "input_format": False,
1602        "serde": False,
1603    }
1604
1605
1606class Partition(Expression):
1607    arg_types = {"expressions": True}
1608
1609
1610class Fetch(Expression):
1611    arg_types = {
1612        "direction": False,
1613        "count": False,
1614        "percent": False,
1615        "with_ties": False,
1616    }
1617
1618
1619class Group(Expression):
1620    arg_types = {
1621        "expressions": False,
1622        "grouping_sets": False,
1623        "cube": False,
1624        "rollup": False,
1625        "totals": False,
1626    }
1627
1628
1629class Lambda(Expression):
1630    arg_types = {"this": True, "expressions": True}
1631
1632
1633class Limit(Expression):
1634    arg_types = {"this": False, "expression": True, "offset": False}
1635
1636
1637class Literal(Condition):
1638    arg_types = {"this": True, "is_string": True}
1639
1640    @property
1641    def hashable_args(self) -> t.Any:
1642        return (self.this, self.args.get("is_string"))
1643
1644    @classmethod
1645    def number(cls, number) -> Literal:
1646        return cls(this=str(number), is_string=False)
1647
1648    @classmethod
1649    def string(cls, string) -> Literal:
1650        return cls(this=str(string), is_string=True)
1651
1652    @property
1653    def output_name(self) -> str:
1654        return self.name
1655
1656
1657class Join(Expression):
1658    arg_types = {
1659        "this": True,
1660        "on": False,
1661        "side": False,
1662        "kind": False,
1663        "using": False,
1664        "method": False,
1665        "global": False,
1666        "hint": False,
1667    }
1668
1669    @property
1670    def method(self) -> str:
1671        return self.text("method").upper()
1672
1673    @property
1674    def kind(self) -> str:
1675        return self.text("kind").upper()
1676
1677    @property
1678    def side(self) -> str:
1679        return self.text("side").upper()
1680
1681    @property
1682    def hint(self) -> str:
1683        return self.text("hint").upper()
1684
1685    @property
1686    def alias_or_name(self) -> str:
1687        return self.this.alias_or_name
1688
1689    def on(
1690        self,
1691        *expressions: t.Optional[ExpOrStr],
1692        append: bool = True,
1693        dialect: DialectType = None,
1694        copy: bool = True,
1695        **opts,
1696    ) -> Join:
1697        """
1698        Append to or set the ON expressions.
1699
1700        Example:
1701            >>> import sqlglot
1702            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1703            'JOIN x ON y = 1'
1704
1705        Args:
1706            *expressions: the SQL code strings to parse.
1707                If an `Expression` instance is passed, it will be used as-is.
1708                Multiple expressions are combined with an AND operator.
1709            append: if `True`, AND the new expressions to any existing expression.
1710                Otherwise, this resets the expression.
1711            dialect: the dialect used to parse the input expressions.
1712            copy: if `False`, modify this expression instance in-place.
1713            opts: other options to use to parse the input expressions.
1714
1715        Returns:
1716            The modified Join expression.
1717        """
1718        join = _apply_conjunction_builder(
1719            *expressions,
1720            instance=self,
1721            arg="on",
1722            append=append,
1723            dialect=dialect,
1724            copy=copy,
1725            **opts,
1726        )
1727
1728        if join.kind == "CROSS":
1729            join.set("kind", None)
1730
1731        return join
1732
1733    def using(
1734        self,
1735        *expressions: t.Optional[ExpOrStr],
1736        append: bool = True,
1737        dialect: DialectType = None,
1738        copy: bool = True,
1739        **opts,
1740    ) -> Join:
1741        """
1742        Append to or set the USING expressions.
1743
1744        Example:
1745            >>> import sqlglot
1746            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1747            'JOIN x USING (foo, bla)'
1748
1749        Args:
1750            *expressions: the SQL code strings to parse.
1751                If an `Expression` instance is passed, it will be used as-is.
1752            append: if `True`, concatenate the new expressions to the existing "using" list.
1753                Otherwise, this resets the expression.
1754            dialect: the dialect used to parse the input expressions.
1755            copy: if `False`, modify this expression instance in-place.
1756            opts: other options to use to parse the input expressions.
1757
1758        Returns:
1759            The modified Join expression.
1760        """
1761        join = _apply_list_builder(
1762            *expressions,
1763            instance=self,
1764            arg="using",
1765            append=append,
1766            dialect=dialect,
1767            copy=copy,
1768            **opts,
1769        )
1770
1771        if join.kind == "CROSS":
1772            join.set("kind", None)
1773
1774        return join
1775
1776
1777class Lateral(UDTF):
1778    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
1779
1780
1781class MatchRecognize(Expression):
1782    arg_types = {
1783        "partition_by": False,
1784        "order": False,
1785        "measures": False,
1786        "rows": False,
1787        "after": False,
1788        "pattern": False,
1789        "define": False,
1790        "alias": False,
1791    }
1792
1793
1794# Clickhouse FROM FINAL modifier
1795# https://clickhouse.com/docs/en/sql-reference/statements/select/from/#final-modifier
1796class Final(Expression):
1797    pass
1798
1799
1800class Offset(Expression):
1801    arg_types = {"this": False, "expression": True}
1802
1803
1804class Order(Expression):
1805    arg_types = {"this": False, "expressions": True}
1806
1807
1808# hive specific sorts
1809# https://cwiki.apache.org/confluence/display/Hive/LanguageManual+SortBy
1810class Cluster(Order):
1811    pass
1812
1813
1814class Distribute(Order):
1815    pass
1816
1817
1818class Sort(Order):
1819    pass
1820
1821
1822class Ordered(Expression):
1823    arg_types = {"this": True, "desc": True, "nulls_first": True}
1824
1825
1826class Property(Expression):
1827    arg_types = {"this": True, "value": True}
1828
1829
1830class AlgorithmProperty(Property):
1831    arg_types = {"this": True}
1832
1833
1834class AutoIncrementProperty(Property):
1835    arg_types = {"this": True}
1836
1837
1838class BlockCompressionProperty(Property):
1839    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
1840
1841
1842class CharacterSetProperty(Property):
1843    arg_types = {"this": True, "default": True}
1844
1845
1846class ChecksumProperty(Property):
1847    arg_types = {"on": False, "default": False}
1848
1849
1850class CollateProperty(Property):
1851    arg_types = {"this": True}
1852
1853
1854class CopyGrantsProperty(Property):
1855    arg_types = {}
1856
1857
1858class DataBlocksizeProperty(Property):
1859    arg_types = {
1860        "size": False,
1861        "units": False,
1862        "minimum": False,
1863        "maximum": False,
1864        "default": False,
1865    }
1866
1867
1868class DefinerProperty(Property):
1869    arg_types = {"this": True}
1870
1871
1872class DistKeyProperty(Property):
1873    arg_types = {"this": True}
1874
1875
1876class DistStyleProperty(Property):
1877    arg_types = {"this": True}
1878
1879
1880class EngineProperty(Property):
1881    arg_types = {"this": True}
1882
1883
1884class ToTableProperty(Property):
1885    arg_types = {"this": True}
1886
1887
1888class ExecuteAsProperty(Property):
1889    arg_types = {"this": True}
1890
1891
1892class ExternalProperty(Property):
1893    arg_types = {"this": False}
1894
1895
1896class FallbackProperty(Property):
1897    arg_types = {"no": True, "protection": False}
1898
1899
1900class FileFormatProperty(Property):
1901    arg_types = {"this": True}
1902
1903
1904class FreespaceProperty(Property):
1905    arg_types = {"this": True, "percent": False}
1906
1907
1908class InputOutputFormat(Expression):
1909    arg_types = {"input_format": False, "output_format": False}
1910
1911
1912class IsolatedLoadingProperty(Property):
1913    arg_types = {
1914        "no": True,
1915        "concurrent": True,
1916        "for_all": True,
1917        "for_insert": True,
1918        "for_none": True,
1919    }
1920
1921
1922class JournalProperty(Property):
1923    arg_types = {
1924        "no": False,
1925        "dual": False,
1926        "before": False,
1927        "local": False,
1928        "after": False,
1929    }
1930
1931
1932class LanguageProperty(Property):
1933    arg_types = {"this": True}
1934
1935
1936class DictProperty(Property):
1937    arg_types = {"this": True, "kind": True, "settings": False}
1938
1939
1940class DictSubProperty(Property):
1941    pass
1942
1943
1944class DictRange(Property):
1945    arg_types = {"this": True, "min": True, "max": True}
1946
1947
1948# Clickhouse CREATE ... ON CLUSTER modifier
1949# https://clickhouse.com/docs/en/sql-reference/distributed-ddl
1950class OnCluster(Property):
1951    arg_types = {"this": True}
1952
1953
1954class LikeProperty(Property):
1955    arg_types = {"this": True, "expressions": False}
1956
1957
1958class LocationProperty(Property):
1959    arg_types = {"this": True}
1960
1961
1962class LockingProperty(Property):
1963    arg_types = {
1964        "this": False,
1965        "kind": True,
1966        "for_or_in": True,
1967        "lock_type": True,
1968        "override": False,
1969    }
1970
1971
1972class LogProperty(Property):
1973    arg_types = {"no": True}
1974
1975
1976class MaterializedProperty(Property):
1977    arg_types = {"this": False}
1978
1979
1980class MergeBlockRatioProperty(Property):
1981    arg_types = {"this": False, "no": False, "default": False, "percent": False}
1982
1983
1984class NoPrimaryIndexProperty(Property):
1985    arg_types = {}
1986
1987
1988class OnCommitProperty(Property):
1989    arg_type = {"delete": False}
1990
1991
1992class PartitionedByProperty(Property):
1993    arg_types = {"this": True}
1994
1995
1996class ReturnsProperty(Property):
1997    arg_types = {"this": True, "is_table": False, "table": False}
1998
1999
2000class RowFormatProperty(Property):
2001    arg_types = {"this": True}
2002
2003
2004class RowFormatDelimitedProperty(Property):
2005    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2006    arg_types = {
2007        "fields": False,
2008        "escaped": False,
2009        "collection_items": False,
2010        "map_keys": False,
2011        "lines": False,
2012        "null": False,
2013        "serde": False,
2014    }
2015
2016
2017class RowFormatSerdeProperty(Property):
2018    arg_types = {"this": True}
2019
2020
2021class SchemaCommentProperty(Property):
2022    arg_types = {"this": True}
2023
2024
2025class SerdeProperties(Property):
2026    arg_types = {"expressions": True}
2027
2028
2029class SetProperty(Property):
2030    arg_types = {"multi": True}
2031
2032
2033class SettingsProperty(Property):
2034    arg_types = {"expressions": True}
2035
2036
2037class SortKeyProperty(Property):
2038    arg_types = {"this": True, "compound": False}
2039
2040
2041class SqlSecurityProperty(Property):
2042    arg_types = {"definer": True}
2043
2044
2045class StabilityProperty(Property):
2046    arg_types = {"this": True}
2047
2048
2049class TemporaryProperty(Property):
2050    arg_types = {}
2051
2052
2053class TransientProperty(Property):
2054    arg_types = {"this": False}
2055
2056
2057class VolatileProperty(Property):
2058    arg_types = {"this": False}
2059
2060
2061class WithDataProperty(Property):
2062    arg_types = {"no": True, "statistics": False}
2063
2064
2065class WithJournalTableProperty(Property):
2066    arg_types = {"this": True}
2067
2068
2069class Properties(Expression):
2070    arg_types = {"expressions": True}
2071
2072    NAME_TO_PROPERTY = {
2073        "ALGORITHM": AlgorithmProperty,
2074        "AUTO_INCREMENT": AutoIncrementProperty,
2075        "CHARACTER SET": CharacterSetProperty,
2076        "COLLATE": CollateProperty,
2077        "COMMENT": SchemaCommentProperty,
2078        "DEFINER": DefinerProperty,
2079        "DISTKEY": DistKeyProperty,
2080        "DISTSTYLE": DistStyleProperty,
2081        "ENGINE": EngineProperty,
2082        "EXECUTE AS": ExecuteAsProperty,
2083        "FORMAT": FileFormatProperty,
2084        "LANGUAGE": LanguageProperty,
2085        "LOCATION": LocationProperty,
2086        "PARTITIONED_BY": PartitionedByProperty,
2087        "RETURNS": ReturnsProperty,
2088        "ROW_FORMAT": RowFormatProperty,
2089        "SORTKEY": SortKeyProperty,
2090    }
2091
2092    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2093
2094    # CREATE property locations
2095    # Form: schema specified
2096    #   create [POST_CREATE]
2097    #     table a [POST_NAME]
2098    #     (b int) [POST_SCHEMA]
2099    #     with ([POST_WITH])
2100    #     index (b) [POST_INDEX]
2101    #
2102    # Form: alias selection
2103    #   create [POST_CREATE]
2104    #     table a [POST_NAME]
2105    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2106    #     index (c) [POST_INDEX]
2107    class Location(AutoName):
2108        POST_CREATE = auto()
2109        POST_NAME = auto()
2110        POST_SCHEMA = auto()
2111        POST_WITH = auto()
2112        POST_ALIAS = auto()
2113        POST_EXPRESSION = auto()
2114        POST_INDEX = auto()
2115        UNSUPPORTED = auto()
2116
2117    @classmethod
2118    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2119        expressions = []
2120        for key, value in properties_dict.items():
2121            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2122            if property_cls:
2123                expressions.append(property_cls(this=convert(value)))
2124            else:
2125                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2126
2127        return cls(expressions=expressions)
2128
2129
2130class Qualify(Expression):
2131    pass
2132
2133
2134# https://www.ibm.com/docs/en/ias?topic=procedures-return-statement-in-sql
2135class Return(Expression):
2136    pass
2137
2138
2139class Reference(Expression):
2140    arg_types = {"this": True, "expressions": False, "options": False}
2141
2142
2143class Tuple(Expression):
2144    arg_types = {"expressions": False}
2145
2146    def isin(
2147        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2148    ) -> In:
2149        return In(
2150            this=_maybe_copy(self, copy),
2151            expressions=[convert(e, copy=copy) for e in expressions],
2152            query=maybe_parse(query, copy=copy, **opts) if query else None,
2153        )
2154
2155
2156class Subqueryable(Unionable):
2157    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2158        """
2159        Convert this expression to an aliased expression that can be used as a Subquery.
2160
2161        Example:
2162            >>> subquery = Select().select("x").from_("tbl").subquery()
2163            >>> Select().select("x").from_(subquery).sql()
2164            'SELECT x FROM (SELECT x FROM tbl)'
2165
2166        Args:
2167            alias (str | Identifier): an optional alias for the subquery
2168            copy (bool): if `False`, modify this expression instance in-place.
2169
2170        Returns:
2171            Alias: the subquery
2172        """
2173        instance = _maybe_copy(self, copy)
2174        if not isinstance(alias, Expression):
2175            alias = TableAlias(this=to_identifier(alias)) if alias else None
2176
2177        return Subquery(this=instance, alias=alias)
2178
2179    def limit(
2180        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2181    ) -> Select:
2182        raise NotImplementedError
2183
2184    @property
2185    def ctes(self):
2186        with_ = self.args.get("with")
2187        if not with_:
2188            return []
2189        return with_.expressions
2190
2191    @property
2192    def selects(self):
2193        raise NotImplementedError("Subqueryable objects must implement `selects`")
2194
2195    @property
2196    def named_selects(self):
2197        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2198
2199    def with_(
2200        self,
2201        alias: ExpOrStr,
2202        as_: ExpOrStr,
2203        recursive: t.Optional[bool] = None,
2204        append: bool = True,
2205        dialect: DialectType = None,
2206        copy: bool = True,
2207        **opts,
2208    ) -> Subqueryable:
2209        """
2210        Append to or set the common table expressions.
2211
2212        Example:
2213            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2214            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2215
2216        Args:
2217            alias: the SQL code string to parse as the table name.
2218                If an `Expression` instance is passed, this is used as-is.
2219            as_: the SQL code string to parse as the table expression.
2220                If an `Expression` instance is passed, it will be used as-is.
2221            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2222            append: if `True`, add to any existing expressions.
2223                Otherwise, this resets the expressions.
2224            dialect: the dialect used to parse the input expression.
2225            copy: if `False`, modify this expression instance in-place.
2226            opts: other options to use to parse the input expressions.
2227
2228        Returns:
2229            The modified expression.
2230        """
2231        return _apply_cte_builder(
2232            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2233        )
2234
2235
2236QUERY_MODIFIERS = {
2237    "match": False,
2238    "laterals": False,
2239    "joins": False,
2240    "pivots": False,
2241    "where": False,
2242    "group": False,
2243    "having": False,
2244    "qualify": False,
2245    "windows": False,
2246    "distribute": False,
2247    "sort": False,
2248    "cluster": False,
2249    "order": False,
2250    "limit": False,
2251    "offset": False,
2252    "locks": False,
2253    "sample": False,
2254    "settings": False,
2255    "format": False,
2256}
2257
2258
2259# https://learn.microsoft.com/en-us/sql/t-sql/queries/hints-transact-sql-table?view=sql-server-ver16
2260class WithTableHint(Expression):
2261    arg_types = {"expressions": True}
2262
2263
2264# https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
2265class IndexTableHint(Expression):
2266    arg_types = {"this": True, "expressions": False, "target": False}
2267
2268
2269class Table(Expression):
2270    arg_types = {
2271        "this": True,
2272        "alias": False,
2273        "db": False,
2274        "catalog": False,
2275        "laterals": False,
2276        "joins": False,
2277        "pivots": False,
2278        "hints": False,
2279        "system_time": False,
2280    }
2281
2282    @property
2283    def db(self) -> str:
2284        return self.text("db")
2285
2286    @property
2287    def catalog(self) -> str:
2288        return self.text("catalog")
2289
2290    @property
2291    def parts(self) -> t.List[Identifier]:
2292        """Return the parts of a table in order catalog, db, table."""
2293        return [
2294            t.cast(Identifier, self.args[part])
2295            for part in ("catalog", "db", "this")
2296            if self.args.get(part)
2297        ]
2298
2299
2300# See the TSQL "Querying data in a system-versioned temporal table" page
2301class SystemTime(Expression):
2302    arg_types = {
2303        "this": False,
2304        "expression": False,
2305        "kind": True,
2306    }
2307
2308
2309class Union(Subqueryable):
2310    arg_types = {
2311        "with": False,
2312        "this": True,
2313        "expression": True,
2314        "distinct": False,
2315        **QUERY_MODIFIERS,
2316    }
2317
2318    def limit(
2319        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2320    ) -> Select:
2321        """
2322        Set the LIMIT expression.
2323
2324        Example:
2325            >>> select("1").union(select("1")).limit(1).sql()
2326            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2327
2328        Args:
2329            expression: the SQL code string to parse.
2330                This can also be an integer.
2331                If a `Limit` instance is passed, this is used as-is.
2332                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2333            dialect: the dialect used to parse the input expression.
2334            copy: if `False`, modify this expression instance in-place.
2335            opts: other options to use to parse the input expressions.
2336
2337        Returns:
2338            The limited subqueryable.
2339        """
2340        return (
2341            select("*")
2342            .from_(self.subquery(alias="_l_0", copy=copy))
2343            .limit(expression, dialect=dialect, copy=False, **opts)
2344        )
2345
2346    def select(
2347        self,
2348        *expressions: t.Optional[ExpOrStr],
2349        append: bool = True,
2350        dialect: DialectType = None,
2351        copy: bool = True,
2352        **opts,
2353    ) -> Union:
2354        """Append to or set the SELECT of the union recursively.
2355
2356        Example:
2357            >>> from sqlglot import parse_one
2358            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2359            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2360
2361        Args:
2362            *expressions: the SQL code strings to parse.
2363                If an `Expression` instance is passed, it will be used as-is.
2364            append: if `True`, add to any existing expressions.
2365                Otherwise, this resets the expressions.
2366            dialect: the dialect used to parse the input expressions.
2367            copy: if `False`, modify this expression instance in-place.
2368            opts: other options to use to parse the input expressions.
2369
2370        Returns:
2371            Union: the modified expression.
2372        """
2373        this = self.copy() if copy else self
2374        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2375        this.expression.unnest().select(
2376            *expressions, append=append, dialect=dialect, copy=False, **opts
2377        )
2378        return this
2379
2380    @property
2381    def named_selects(self):
2382        return self.this.unnest().named_selects
2383
2384    @property
2385    def is_star(self) -> bool:
2386        return self.this.is_star or self.expression.is_star
2387
2388    @property
2389    def selects(self):
2390        return self.this.unnest().selects
2391
2392    @property
2393    def left(self):
2394        return self.this
2395
2396    @property
2397    def right(self):
2398        return self.expression
2399
2400
2401class Except(Union):
2402    pass
2403
2404
2405class Intersect(Union):
2406    pass
2407
2408
2409class Unnest(UDTF):
2410    arg_types = {
2411        "expressions": True,
2412        "ordinality": False,
2413        "alias": False,
2414        "offset": False,
2415    }
2416
2417
2418class Update(Expression):
2419    arg_types = {
2420        "with": False,
2421        "this": False,
2422        "expressions": True,
2423        "from": False,
2424        "where": False,
2425        "returning": False,
2426        "limit": False,
2427    }
2428
2429
2430class Values(UDTF):
2431    arg_types = {
2432        "expressions": True,
2433        "ordinality": False,
2434        "alias": False,
2435    }
2436
2437
2438class Var(Expression):
2439    pass
2440
2441
2442class Schema(Expression):
2443    arg_types = {"this": False, "expressions": False}
2444
2445
2446# https://dev.mysql.com/doc/refman/8.0/en/select.html
2447# https://docs.oracle.com/en/database/oracle/oracle-database/19/sqlrf/SELECT.html
2448class Lock(Expression):
2449    arg_types = {"update": True, "expressions": False, "wait": False}
2450
2451
2452class Select(Subqueryable):
2453    arg_types = {
2454        "with": False,
2455        "kind": False,
2456        "expressions": False,
2457        "hint": False,
2458        "distinct": False,
2459        "into": False,
2460        "from": False,
2461        **QUERY_MODIFIERS,
2462    }
2463
2464    def from_(
2465        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2466    ) -> Select:
2467        """
2468        Set the FROM expression.
2469
2470        Example:
2471            >>> Select().from_("tbl").select("x").sql()
2472            'SELECT x FROM tbl'
2473
2474        Args:
2475            expression : the SQL code strings to parse.
2476                If a `From` instance is passed, this is used as-is.
2477                If another `Expression` instance is passed, it will be wrapped in a `From`.
2478            dialect: the dialect used to parse the input expression.
2479            copy: if `False`, modify this expression instance in-place.
2480            opts: other options to use to parse the input expressions.
2481
2482        Returns:
2483            The modified Select expression.
2484        """
2485        return _apply_builder(
2486            expression=expression,
2487            instance=self,
2488            arg="from",
2489            into=From,
2490            prefix="FROM",
2491            dialect=dialect,
2492            copy=copy,
2493            **opts,
2494        )
2495
2496    def group_by(
2497        self,
2498        *expressions: t.Optional[ExpOrStr],
2499        append: bool = True,
2500        dialect: DialectType = None,
2501        copy: bool = True,
2502        **opts,
2503    ) -> Select:
2504        """
2505        Set the GROUP BY expression.
2506
2507        Example:
2508            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2509            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2510
2511        Args:
2512            *expressions: the SQL code strings to parse.
2513                If a `Group` instance is passed, this is used as-is.
2514                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2515                If nothing is passed in then a group by is not applied to the expression
2516            append: if `True`, add to any existing expressions.
2517                Otherwise, this flattens all the `Group` expression into a single expression.
2518            dialect: the dialect used to parse the input expression.
2519            copy: if `False`, modify this expression instance in-place.
2520            opts: other options to use to parse the input expressions.
2521
2522        Returns:
2523            The modified Select expression.
2524        """
2525        if not expressions:
2526            return self if not copy else self.copy()
2527
2528        return _apply_child_list_builder(
2529            *expressions,
2530            instance=self,
2531            arg="group",
2532            append=append,
2533            copy=copy,
2534            prefix="GROUP BY",
2535            into=Group,
2536            dialect=dialect,
2537            **opts,
2538        )
2539
2540    def order_by(
2541        self,
2542        *expressions: t.Optional[ExpOrStr],
2543        append: bool = True,
2544        dialect: DialectType = None,
2545        copy: bool = True,
2546        **opts,
2547    ) -> Select:
2548        """
2549        Set the ORDER BY expression.
2550
2551        Example:
2552            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2553            'SELECT x FROM tbl ORDER BY x DESC'
2554
2555        Args:
2556            *expressions: the SQL code strings to parse.
2557                If a `Group` instance is passed, this is used as-is.
2558                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2559            append: if `True`, add to any existing expressions.
2560                Otherwise, this flattens all the `Order` expression into a single expression.
2561            dialect: the dialect used to parse the input expression.
2562            copy: if `False`, modify this expression instance in-place.
2563            opts: other options to use to parse the input expressions.
2564
2565        Returns:
2566            The modified Select expression.
2567        """
2568        return _apply_child_list_builder(
2569            *expressions,
2570            instance=self,
2571            arg="order",
2572            append=append,
2573            copy=copy,
2574            prefix="ORDER BY",
2575            into=Order,
2576            dialect=dialect,
2577            **opts,
2578        )
2579
2580    def sort_by(
2581        self,
2582        *expressions: t.Optional[ExpOrStr],
2583        append: bool = True,
2584        dialect: DialectType = None,
2585        copy: bool = True,
2586        **opts,
2587    ) -> Select:
2588        """
2589        Set the SORT BY expression.
2590
2591        Example:
2592            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2593            'SELECT x FROM tbl SORT BY x DESC'
2594
2595        Args:
2596            *expressions: the SQL code strings to parse.
2597                If a `Group` instance is passed, this is used as-is.
2598                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2599            append: if `True`, add to any existing expressions.
2600                Otherwise, this flattens all the `Order` expression into a single expression.
2601            dialect: the dialect used to parse the input expression.
2602            copy: if `False`, modify this expression instance in-place.
2603            opts: other options to use to parse the input expressions.
2604
2605        Returns:
2606            The modified Select expression.
2607        """
2608        return _apply_child_list_builder(
2609            *expressions,
2610            instance=self,
2611            arg="sort",
2612            append=append,
2613            copy=copy,
2614            prefix="SORT BY",
2615            into=Sort,
2616            dialect=dialect,
2617            **opts,
2618        )
2619
2620    def cluster_by(
2621        self,
2622        *expressions: t.Optional[ExpOrStr],
2623        append: bool = True,
2624        dialect: DialectType = None,
2625        copy: bool = True,
2626        **opts,
2627    ) -> Select:
2628        """
2629        Set the CLUSTER BY expression.
2630
2631        Example:
2632            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2633            'SELECT x FROM tbl CLUSTER BY x DESC'
2634
2635        Args:
2636            *expressions: the SQL code strings to parse.
2637                If a `Group` instance is passed, this is used as-is.
2638                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2639            append: if `True`, add to any existing expressions.
2640                Otherwise, this flattens all the `Order` expression into a single expression.
2641            dialect: the dialect used to parse the input expression.
2642            copy: if `False`, modify this expression instance in-place.
2643            opts: other options to use to parse the input expressions.
2644
2645        Returns:
2646            The modified Select expression.
2647        """
2648        return _apply_child_list_builder(
2649            *expressions,
2650            instance=self,
2651            arg="cluster",
2652            append=append,
2653            copy=copy,
2654            prefix="CLUSTER BY",
2655            into=Cluster,
2656            dialect=dialect,
2657            **opts,
2658        )
2659
2660    def limit(
2661        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2662    ) -> Select:
2663        """
2664        Set the LIMIT expression.
2665
2666        Example:
2667            >>> Select().from_("tbl").select("x").limit(10).sql()
2668            'SELECT x FROM tbl LIMIT 10'
2669
2670        Args:
2671            expression: the SQL code string to parse.
2672                This can also be an integer.
2673                If a `Limit` instance is passed, this is used as-is.
2674                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2675            dialect: the dialect used to parse the input expression.
2676            copy: if `False`, modify this expression instance in-place.
2677            opts: other options to use to parse the input expressions.
2678
2679        Returns:
2680            Select: the modified expression.
2681        """
2682        return _apply_builder(
2683            expression=expression,
2684            instance=self,
2685            arg="limit",
2686            into=Limit,
2687            prefix="LIMIT",
2688            dialect=dialect,
2689            copy=copy,
2690            **opts,
2691        )
2692
2693    def offset(
2694        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2695    ) -> Select:
2696        """
2697        Set the OFFSET expression.
2698
2699        Example:
2700            >>> Select().from_("tbl").select("x").offset(10).sql()
2701            'SELECT x FROM tbl OFFSET 10'
2702
2703        Args:
2704            expression: the SQL code string to parse.
2705                This can also be an integer.
2706                If a `Offset` instance is passed, this is used as-is.
2707                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2708            dialect: the dialect used to parse the input expression.
2709            copy: if `False`, modify this expression instance in-place.
2710            opts: other options to use to parse the input expressions.
2711
2712        Returns:
2713            The modified Select expression.
2714        """
2715        return _apply_builder(
2716            expression=expression,
2717            instance=self,
2718            arg="offset",
2719            into=Offset,
2720            prefix="OFFSET",
2721            dialect=dialect,
2722            copy=copy,
2723            **opts,
2724        )
2725
2726    def select(
2727        self,
2728        *expressions: t.Optional[ExpOrStr],
2729        append: bool = True,
2730        dialect: DialectType = None,
2731        copy: bool = True,
2732        **opts,
2733    ) -> Select:
2734        """
2735        Append to or set the SELECT expressions.
2736
2737        Example:
2738            >>> Select().select("x", "y").sql()
2739            'SELECT x, y'
2740
2741        Args:
2742            *expressions: the SQL code strings to parse.
2743                If an `Expression` instance is passed, it will be used as-is.
2744            append: if `True`, add to any existing expressions.
2745                Otherwise, this resets the expressions.
2746            dialect: the dialect used to parse the input expressions.
2747            copy: if `False`, modify this expression instance in-place.
2748            opts: other options to use to parse the input expressions.
2749
2750        Returns:
2751            The modified Select expression.
2752        """
2753        return _apply_list_builder(
2754            *expressions,
2755            instance=self,
2756            arg="expressions",
2757            append=append,
2758            dialect=dialect,
2759            copy=copy,
2760            **opts,
2761        )
2762
2763    def lateral(
2764        self,
2765        *expressions: t.Optional[ExpOrStr],
2766        append: bool = True,
2767        dialect: DialectType = None,
2768        copy: bool = True,
2769        **opts,
2770    ) -> Select:
2771        """
2772        Append to or set the LATERAL expressions.
2773
2774        Example:
2775            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2776            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2777
2778        Args:
2779            *expressions: the SQL code strings to parse.
2780                If an `Expression` instance is passed, it will be used as-is.
2781            append: if `True`, add to any existing expressions.
2782                Otherwise, this resets the expressions.
2783            dialect: the dialect used to parse the input expressions.
2784            copy: if `False`, modify this expression instance in-place.
2785            opts: other options to use to parse the input expressions.
2786
2787        Returns:
2788            The modified Select expression.
2789        """
2790        return _apply_list_builder(
2791            *expressions,
2792            instance=self,
2793            arg="laterals",
2794            append=append,
2795            into=Lateral,
2796            prefix="LATERAL VIEW",
2797            dialect=dialect,
2798            copy=copy,
2799            **opts,
2800        )
2801
2802    def join(
2803        self,
2804        expression: ExpOrStr,
2805        on: t.Optional[ExpOrStr] = None,
2806        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2807        append: bool = True,
2808        join_type: t.Optional[str] = None,
2809        join_alias: t.Optional[Identifier | str] = None,
2810        dialect: DialectType = None,
2811        copy: bool = True,
2812        **opts,
2813    ) -> Select:
2814        """
2815        Append to or set the JOIN expressions.
2816
2817        Example:
2818            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2819            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2820
2821            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2822            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2823
2824            Use `join_type` to change the type of join:
2825
2826            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2827            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2828
2829        Args:
2830            expression: the SQL code string to parse.
2831                If an `Expression` instance is passed, it will be used as-is.
2832            on: optionally specify the join "on" criteria as a SQL string.
2833                If an `Expression` instance is passed, it will be used as-is.
2834            using: optionally specify the join "using" criteria as a SQL string.
2835                If an `Expression` instance is passed, it will be used as-is.
2836            append: if `True`, add to any existing expressions.
2837                Otherwise, this resets the expressions.
2838            join_type: if set, alter the parsed join type.
2839            join_alias: an optional alias for the joined source.
2840            dialect: the dialect used to parse the input expressions.
2841            copy: if `False`, modify this expression instance in-place.
2842            opts: other options to use to parse the input expressions.
2843
2844        Returns:
2845            Select: the modified expression.
2846        """
2847        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2848
2849        try:
2850            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2851        except ParseError:
2852            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2853
2854        join = expression if isinstance(expression, Join) else Join(this=expression)
2855
2856        if isinstance(join.this, Select):
2857            join.this.replace(join.this.subquery())
2858
2859        if join_type:
2860            method: t.Optional[Token]
2861            side: t.Optional[Token]
2862            kind: t.Optional[Token]
2863
2864            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2865
2866            if method:
2867                join.set("method", method.text)
2868            if side:
2869                join.set("side", side.text)
2870            if kind:
2871                join.set("kind", kind.text)
2872
2873        if on:
2874            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2875            join.set("on", on)
2876
2877        if using:
2878            join = _apply_list_builder(
2879                *ensure_list(using),
2880                instance=join,
2881                arg="using",
2882                append=append,
2883                copy=copy,
2884                **opts,
2885            )
2886
2887        if join_alias:
2888            join.set("this", alias_(join.this, join_alias, table=True))
2889
2890        return _apply_list_builder(
2891            join,
2892            instance=self,
2893            arg="joins",
2894            append=append,
2895            copy=copy,
2896            **opts,
2897        )
2898
2899    def where(
2900        self,
2901        *expressions: t.Optional[ExpOrStr],
2902        append: bool = True,
2903        dialect: DialectType = None,
2904        copy: bool = True,
2905        **opts,
2906    ) -> Select:
2907        """
2908        Append to or set the WHERE expressions.
2909
2910        Example:
2911            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2912            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2913
2914        Args:
2915            *expressions: the SQL code strings to parse.
2916                If an `Expression` instance is passed, it will be used as-is.
2917                Multiple expressions are combined with an AND operator.
2918            append: if `True`, AND the new expressions to any existing expression.
2919                Otherwise, this resets the expression.
2920            dialect: the dialect used to parse the input expressions.
2921            copy: if `False`, modify this expression instance in-place.
2922            opts: other options to use to parse the input expressions.
2923
2924        Returns:
2925            Select: the modified expression.
2926        """
2927        return _apply_conjunction_builder(
2928            *expressions,
2929            instance=self,
2930            arg="where",
2931            append=append,
2932            into=Where,
2933            dialect=dialect,
2934            copy=copy,
2935            **opts,
2936        )
2937
2938    def having(
2939        self,
2940        *expressions: t.Optional[ExpOrStr],
2941        append: bool = True,
2942        dialect: DialectType = None,
2943        copy: bool = True,
2944        **opts,
2945    ) -> Select:
2946        """
2947        Append to or set the HAVING expressions.
2948
2949        Example:
2950            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2951            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2952
2953        Args:
2954            *expressions: the SQL code strings to parse.
2955                If an `Expression` instance is passed, it will be used as-is.
2956                Multiple expressions are combined with an AND operator.
2957            append: if `True`, AND the new expressions to any existing expression.
2958                Otherwise, this resets the expression.
2959            dialect: the dialect used to parse the input expressions.
2960            copy: if `False`, modify this expression instance in-place.
2961            opts: other options to use to parse the input expressions.
2962
2963        Returns:
2964            The modified Select expression.
2965        """
2966        return _apply_conjunction_builder(
2967            *expressions,
2968            instance=self,
2969            arg="having",
2970            append=append,
2971            into=Having,
2972            dialect=dialect,
2973            copy=copy,
2974            **opts,
2975        )
2976
2977    def window(
2978        self,
2979        *expressions: t.Optional[ExpOrStr],
2980        append: bool = True,
2981        dialect: DialectType = None,
2982        copy: bool = True,
2983        **opts,
2984    ) -> Select:
2985        return _apply_list_builder(
2986            *expressions,
2987            instance=self,
2988            arg="windows",
2989            append=append,
2990            into=Window,
2991            dialect=dialect,
2992            copy=copy,
2993            **opts,
2994        )
2995
2996    def qualify(
2997        self,
2998        *expressions: t.Optional[ExpOrStr],
2999        append: bool = True,
3000        dialect: DialectType = None,
3001        copy: bool = True,
3002        **opts,
3003    ) -> Select:
3004        return _apply_conjunction_builder(
3005            *expressions,
3006            instance=self,
3007            arg="qualify",
3008            append=append,
3009            into=Qualify,
3010            dialect=dialect,
3011            copy=copy,
3012            **opts,
3013        )
3014
3015    def distinct(
3016        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3017    ) -> Select:
3018        """
3019        Set the OFFSET expression.
3020
3021        Example:
3022            >>> Select().from_("tbl").select("x").distinct().sql()
3023            'SELECT DISTINCT x FROM tbl'
3024
3025        Args:
3026            ons: the expressions to distinct on
3027            distinct: whether the Select should be distinct
3028            copy: if `False`, modify this expression instance in-place.
3029
3030        Returns:
3031            Select: the modified expression.
3032        """
3033        instance = _maybe_copy(self, copy)
3034        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3035        instance.set("distinct", Distinct(on=on) if distinct else None)
3036        return instance
3037
3038    def ctas(
3039        self,
3040        table: ExpOrStr,
3041        properties: t.Optional[t.Dict] = None,
3042        dialect: DialectType = None,
3043        copy: bool = True,
3044        **opts,
3045    ) -> Create:
3046        """
3047        Convert this expression to a CREATE TABLE AS statement.
3048
3049        Example:
3050            >>> Select().select("*").from_("tbl").ctas("x").sql()
3051            'CREATE TABLE x AS SELECT * FROM tbl'
3052
3053        Args:
3054            table: the SQL code string to parse as the table name.
3055                If another `Expression` instance is passed, it will be used as-is.
3056            properties: an optional mapping of table properties
3057            dialect: the dialect used to parse the input table.
3058            copy: if `False`, modify this expression instance in-place.
3059            opts: other options to use to parse the input table.
3060
3061        Returns:
3062            The new Create expression.
3063        """
3064        instance = _maybe_copy(self, copy)
3065        table_expression = maybe_parse(
3066            table,
3067            into=Table,
3068            dialect=dialect,
3069            **opts,
3070        )
3071        properties_expression = None
3072        if properties:
3073            properties_expression = Properties.from_dict(properties)
3074
3075        return Create(
3076            this=table_expression,
3077            kind="table",
3078            expression=instance,
3079            properties=properties_expression,
3080        )
3081
3082    def lock(self, update: bool = True, copy: bool = True) -> Select:
3083        """
3084        Set the locking read mode for this expression.
3085
3086        Examples:
3087            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3088            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3089
3090            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3091            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3092
3093        Args:
3094            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3095            copy: if `False`, modify this expression instance in-place.
3096
3097        Returns:
3098            The modified expression.
3099        """
3100        inst = _maybe_copy(self, copy)
3101        inst.set("locks", [Lock(update=update)])
3102
3103        return inst
3104
3105    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3106        """
3107        Set hints for this expression.
3108
3109        Examples:
3110            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3111            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3112
3113        Args:
3114            hints: The SQL code strings to parse as the hints.
3115                If an `Expression` instance is passed, it will be used as-is.
3116            dialect: The dialect used to parse the hints.
3117            copy: If `False`, modify this expression instance in-place.
3118
3119        Returns:
3120            The modified expression.
3121        """
3122        inst = _maybe_copy(self, copy)
3123        inst.set(
3124            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3125        )
3126
3127        return inst
3128
3129    @property
3130    def named_selects(self) -> t.List[str]:
3131        return [e.output_name for e in self.expressions if e.alias_or_name]
3132
3133    @property
3134    def is_star(self) -> bool:
3135        return any(expression.is_star for expression in self.expressions)
3136
3137    @property
3138    def selects(self) -> t.List[Expression]:
3139        return self.expressions
3140
3141
3142class Subquery(DerivedTable, Unionable):
3143    arg_types = {
3144        "this": True,
3145        "alias": False,
3146        "with": False,
3147        **QUERY_MODIFIERS,
3148    }
3149
3150    def unnest(self):
3151        """
3152        Returns the first non subquery.
3153        """
3154        expression = self
3155        while isinstance(expression, Subquery):
3156            expression = expression.this
3157        return expression
3158
3159    @property
3160    def is_star(self) -> bool:
3161        return self.this.is_star
3162
3163    @property
3164    def output_name(self) -> str:
3165        return self.alias
3166
3167
3168class TableSample(Expression):
3169    arg_types = {
3170        "this": False,
3171        "method": False,
3172        "bucket_numerator": False,
3173        "bucket_denominator": False,
3174        "bucket_field": False,
3175        "percent": False,
3176        "rows": False,
3177        "size": False,
3178        "seed": False,
3179        "kind": False,
3180    }
3181
3182
3183class Tag(Expression):
3184    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3185
3186    arg_types = {
3187        "this": False,
3188        "prefix": False,
3189        "postfix": False,
3190    }
3191
3192
3193# Represents both the standard SQL PIVOT operator and DuckDB's "simplified" PIVOT syntax
3194# https://duckdb.org/docs/sql/statements/pivot
3195class Pivot(Expression):
3196    arg_types = {
3197        "this": False,
3198        "alias": False,
3199        "expressions": True,
3200        "field": False,
3201        "unpivot": False,
3202        "using": False,
3203        "group": False,
3204        "columns": False,
3205    }
3206
3207
3208class Window(Expression):
3209    arg_types = {
3210        "this": True,
3211        "partition_by": False,
3212        "order": False,
3213        "spec": False,
3214        "alias": False,
3215        "over": False,
3216        "first": False,
3217    }
3218
3219
3220class WindowSpec(Expression):
3221    arg_types = {
3222        "kind": False,
3223        "start": False,
3224        "start_side": False,
3225        "end": False,
3226        "end_side": False,
3227    }
3228
3229
3230class Where(Expression):
3231    pass
3232
3233
3234class Star(Expression):
3235    arg_types = {"except": False, "replace": False}
3236
3237    @property
3238    def name(self) -> str:
3239        return "*"
3240
3241    @property
3242    def output_name(self) -> str:
3243        return self.name
3244
3245
3246class Parameter(Condition):
3247    arg_types = {"this": True, "wrapped": False}
3248
3249
3250class SessionParameter(Condition):
3251    arg_types = {"this": True, "kind": False}
3252
3253
3254class Placeholder(Condition):
3255    arg_types = {"this": False, "kind": False}
3256
3257
3258class Null(Condition):
3259    arg_types: t.Dict[str, t.Any] = {}
3260
3261    @property
3262    def name(self) -> str:
3263        return "NULL"
3264
3265
3266class Boolean(Condition):
3267    pass
3268
3269
3270class DataTypeSize(Expression):
3271    arg_types = {"this": True, "expression": False}
3272
3273
3274class DataType(Expression):
3275    arg_types = {
3276        "this": True,
3277        "expressions": False,
3278        "nested": False,
3279        "values": False,
3280        "prefix": False,
3281    }
3282
3283    class Type(AutoName):
3284        ARRAY = auto()
3285        BIGDECIMAL = auto()
3286        BIGINT = auto()
3287        BIGSERIAL = auto()
3288        BINARY = auto()
3289        BIT = auto()
3290        BOOLEAN = auto()
3291        CHAR = auto()
3292        DATE = auto()
3293        DATETIME = auto()
3294        DATETIME64 = auto()
3295        ENUM = auto()
3296        INT4RANGE = auto()
3297        INT4MULTIRANGE = auto()
3298        INT8RANGE = auto()
3299        INT8MULTIRANGE = auto()
3300        NUMRANGE = auto()
3301        NUMMULTIRANGE = auto()
3302        TSRANGE = auto()
3303        TSMULTIRANGE = auto()
3304        TSTZRANGE = auto()
3305        TSTZMULTIRANGE = auto()
3306        DATERANGE = auto()
3307        DATEMULTIRANGE = auto()
3308        DECIMAL = auto()
3309        DOUBLE = auto()
3310        FLOAT = auto()
3311        GEOGRAPHY = auto()
3312        GEOMETRY = auto()
3313        HLLSKETCH = auto()
3314        HSTORE = auto()
3315        IMAGE = auto()
3316        INET = auto()
3317        INT = auto()
3318        INT128 = auto()
3319        INT256 = auto()
3320        INTERVAL = auto()
3321        JSON = auto()
3322        JSONB = auto()
3323        LONGBLOB = auto()
3324        LONGTEXT = auto()
3325        MAP = auto()
3326        MEDIUMBLOB = auto()
3327        MEDIUMTEXT = auto()
3328        MONEY = auto()
3329        NCHAR = auto()
3330        NULL = auto()
3331        NULLABLE = auto()
3332        NVARCHAR = auto()
3333        OBJECT = auto()
3334        ROWVERSION = auto()
3335        SERIAL = auto()
3336        SET = auto()
3337        SMALLINT = auto()
3338        SMALLMONEY = auto()
3339        SMALLSERIAL = auto()
3340        STRUCT = auto()
3341        SUPER = auto()
3342        TEXT = auto()
3343        TIME = auto()
3344        TIMESTAMP = auto()
3345        TIMESTAMPTZ = auto()
3346        TIMESTAMPLTZ = auto()
3347        TINYINT = auto()
3348        UBIGINT = auto()
3349        UINT = auto()
3350        USMALLINT = auto()
3351        UTINYINT = auto()
3352        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3353        UINT128 = auto()
3354        UINT256 = auto()
3355        UNIQUEIDENTIFIER = auto()
3356        USERDEFINED = "USER-DEFINED"
3357        UUID = auto()
3358        VARBINARY = auto()
3359        VARCHAR = auto()
3360        VARIANT = auto()
3361        XML = auto()
3362
3363    TEXT_TYPES = {
3364        Type.CHAR,
3365        Type.NCHAR,
3366        Type.VARCHAR,
3367        Type.NVARCHAR,
3368        Type.TEXT,
3369    }
3370
3371    INTEGER_TYPES = {
3372        Type.INT,
3373        Type.TINYINT,
3374        Type.SMALLINT,
3375        Type.BIGINT,
3376        Type.INT128,
3377        Type.INT256,
3378    }
3379
3380    FLOAT_TYPES = {
3381        Type.FLOAT,
3382        Type.DOUBLE,
3383    }
3384
3385    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3386
3387    TEMPORAL_TYPES = {
3388        Type.TIME,
3389        Type.TIMESTAMP,
3390        Type.TIMESTAMPTZ,
3391        Type.TIMESTAMPLTZ,
3392        Type.DATE,
3393        Type.DATETIME,
3394        Type.DATETIME64,
3395    }
3396
3397    META_TYPES = {"UNKNOWN", "NULL"}
3398
3399    @classmethod
3400    def build(
3401        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3402    ) -> DataType:
3403        from sqlglot import parse_one
3404
3405        if isinstance(dtype, str):
3406            upper = dtype.upper()
3407            if upper in DataType.META_TYPES:
3408                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3409            else:
3410                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3411
3412            if data_type_exp is None:
3413                raise ValueError(f"Unparsable data type value: {dtype}")
3414        elif isinstance(dtype, DataType.Type):
3415            data_type_exp = DataType(this=dtype)
3416        elif isinstance(dtype, DataType):
3417            return dtype
3418        else:
3419            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3420
3421        return DataType(**{**data_type_exp.args, **kwargs})
3422
3423    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3424        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
3425
3426
3427# https://www.postgresql.org/docs/15/datatype-pseudo.html
3428class PseudoType(Expression):
3429    pass
3430
3431
3432# WHERE x <OP> EXISTS|ALL|ANY|SOME(SELECT ...)
3433class SubqueryPredicate(Predicate):
3434    pass
3435
3436
3437class All(SubqueryPredicate):
3438    pass
3439
3440
3441class Any(SubqueryPredicate):
3442    pass
3443
3444
3445class Exists(SubqueryPredicate):
3446    pass
3447
3448
3449# Commands to interact with the databases or engines. For most of the command
3450# expressions we parse whatever comes after the command's name as a string.
3451class Command(Expression):
3452    arg_types = {"this": True, "expression": False}
3453
3454
3455class Transaction(Expression):
3456    arg_types = {"this": False, "modes": False}
3457
3458
3459class Commit(Expression):
3460    arg_types = {"chain": False}
3461
3462
3463class Rollback(Expression):
3464    arg_types = {"savepoint": False}
3465
3466
3467class AlterTable(Expression):
3468    arg_types = {"this": True, "actions": True, "exists": False}
3469
3470
3471class AddConstraint(Expression):
3472    arg_types = {"this": False, "expression": False, "enforced": False}
3473
3474
3475class DropPartition(Expression):
3476    arg_types = {"expressions": True, "exists": False}
3477
3478
3479# Binary expressions like (ADD a b)
3480class Binary(Condition):
3481    arg_types = {"this": True, "expression": True}
3482
3483    @property
3484    def left(self):
3485        return self.this
3486
3487    @property
3488    def right(self):
3489        return self.expression
3490
3491
3492class Add(Binary):
3493    pass
3494
3495
3496class Connector(Binary):
3497    pass
3498
3499
3500class And(Connector):
3501    pass
3502
3503
3504class Or(Connector):
3505    pass
3506
3507
3508class BitwiseAnd(Binary):
3509    pass
3510
3511
3512class BitwiseLeftShift(Binary):
3513    pass
3514
3515
3516class BitwiseOr(Binary):
3517    pass
3518
3519
3520class BitwiseRightShift(Binary):
3521    pass
3522
3523
3524class BitwiseXor(Binary):
3525    pass
3526
3527
3528class Div(Binary):
3529    pass
3530
3531
3532class Overlaps(Binary):
3533    pass
3534
3535
3536class Dot(Binary):
3537    @property
3538    def name(self) -> str:
3539        return self.expression.name
3540
3541    @property
3542    def output_name(self) -> str:
3543        return self.name
3544
3545    @classmethod
3546    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3547        """Build a Dot object with a sequence of expressions."""
3548        if len(expressions) < 2:
3549            raise ValueError(f"Dot requires >= 2 expressions.")
3550
3551        a, b, *expressions = expressions
3552        dot = Dot(this=a, expression=b)
3553
3554        for expression in expressions:
3555            dot = Dot(this=dot, expression=expression)
3556
3557        return dot
3558
3559
3560class DPipe(Binary):
3561    pass
3562
3563
3564class SafeDPipe(DPipe):
3565    pass
3566
3567
3568class EQ(Binary, Predicate):
3569    pass
3570
3571
3572class NullSafeEQ(Binary, Predicate):
3573    pass
3574
3575
3576class NullSafeNEQ(Binary, Predicate):
3577    pass
3578
3579
3580class Distance(Binary):
3581    pass
3582
3583
3584class Escape(Binary):
3585    pass
3586
3587
3588class Glob(Binary, Predicate):
3589    pass
3590
3591
3592class GT(Binary, Predicate):
3593    pass
3594
3595
3596class GTE(Binary, Predicate):
3597    pass
3598
3599
3600class ILike(Binary, Predicate):
3601    pass
3602
3603
3604class ILikeAny(Binary, Predicate):
3605    pass
3606
3607
3608class IntDiv(Binary):
3609    pass
3610
3611
3612class Is(Binary, Predicate):
3613    pass
3614
3615
3616class Kwarg(Binary):
3617    """Kwarg in special functions like func(kwarg => y)."""
3618
3619
3620class Like(Binary, Predicate):
3621    pass
3622
3623
3624class LikeAny(Binary, Predicate):
3625    pass
3626
3627
3628class LT(Binary, Predicate):
3629    pass
3630
3631
3632class LTE(Binary, Predicate):
3633    pass
3634
3635
3636class Mod(Binary):
3637    pass
3638
3639
3640class Mul(Binary):
3641    pass
3642
3643
3644class NEQ(Binary, Predicate):
3645    pass
3646
3647
3648class SimilarTo(Binary, Predicate):
3649    pass
3650
3651
3652class Slice(Binary):
3653    arg_types = {"this": False, "expression": False}
3654
3655
3656class Sub(Binary):
3657    pass
3658
3659
3660class ArrayOverlaps(Binary):
3661    pass
3662
3663
3664# Unary Expressions
3665# (NOT a)
3666class Unary(Condition):
3667    pass
3668
3669
3670class BitwiseNot(Unary):
3671    pass
3672
3673
3674class Not(Unary):
3675    pass
3676
3677
3678class Paren(Unary):
3679    arg_types = {"this": True, "with": False}
3680
3681    @property
3682    def output_name(self) -> str:
3683        return self.this.name
3684
3685
3686class Neg(Unary):
3687    pass
3688
3689
3690class Alias(Expression):
3691    arg_types = {"this": True, "alias": False}
3692
3693    @property
3694    def output_name(self) -> str:
3695        return self.alias
3696
3697
3698class Aliases(Expression):
3699    arg_types = {"this": True, "expressions": True}
3700
3701    @property
3702    def aliases(self):
3703        return self.expressions
3704
3705
3706class AtTimeZone(Expression):
3707    arg_types = {"this": True, "zone": True}
3708
3709
3710class Between(Predicate):
3711    arg_types = {"this": True, "low": True, "high": True}
3712
3713
3714class Bracket(Condition):
3715    arg_types = {"this": True, "expressions": True}
3716
3717
3718class Distinct(Expression):
3719    arg_types = {"expressions": False, "on": False}
3720
3721
3722class In(Predicate):
3723    arg_types = {
3724        "this": True,
3725        "expressions": False,
3726        "query": False,
3727        "unnest": False,
3728        "field": False,
3729        "is_global": False,
3730    }
3731
3732
3733class TimeUnit(Expression):
3734    """Automatically converts unit arg into a var."""
3735
3736    arg_types = {"unit": False}
3737
3738    def __init__(self, **args):
3739        unit = args.get("unit")
3740        if isinstance(unit, (Column, Literal)):
3741            args["unit"] = Var(this=unit.name)
3742        elif isinstance(unit, Week):
3743            unit.set("this", Var(this=unit.this.name))
3744
3745        super().__init__(**args)
3746
3747
3748class Interval(TimeUnit):
3749    arg_types = {"this": False, "unit": False}
3750
3751    @property
3752    def unit(self) -> t.Optional[Var]:
3753        return self.args.get("unit")
3754
3755
3756class IgnoreNulls(Expression):
3757    pass
3758
3759
3760class RespectNulls(Expression):
3761    pass
3762
3763
3764# Functions
3765class Func(Condition):
3766    """
3767    The base class for all function expressions.
3768
3769    Attributes:
3770        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3771            treated as a variable length argument and the argument's value will be stored as a list.
3772        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3773            for this function expression. These values are used to map this node to a name during parsing
3774            as well as to provide the function's name during SQL string generation. By default the SQL
3775            name is set to the expression's class name transformed to snake case.
3776    """
3777
3778    is_var_len_args = False
3779
3780    @classmethod
3781    def from_arg_list(cls, args):
3782        if cls.is_var_len_args:
3783            all_arg_keys = list(cls.arg_types)
3784            # If this function supports variable length argument treat the last argument as such.
3785            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3786            num_non_var = len(non_var_len_arg_keys)
3787
3788            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3789            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3790        else:
3791            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3792
3793        return cls(**args_dict)
3794
3795    @classmethod
3796    def sql_names(cls):
3797        if cls is Func:
3798            raise NotImplementedError(
3799                "SQL name is only supported by concrete function implementations"
3800            )
3801        if "_sql_names" not in cls.__dict__:
3802            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3803        return cls._sql_names
3804
3805    @classmethod
3806    def sql_name(cls):
3807        return cls.sql_names()[0]
3808
3809    @classmethod
3810    def default_parser_mappings(cls):
3811        return {name: cls.from_arg_list for name in cls.sql_names()}
3812
3813
3814class AggFunc(Func):
3815    pass
3816
3817
3818class ParameterizedAgg(AggFunc):
3819    arg_types = {"this": True, "expressions": True, "params": True}
3820
3821
3822class Abs(Func):
3823    pass
3824
3825
3826class Anonymous(Func):
3827    arg_types = {"this": True, "expressions": False}
3828    is_var_len_args = True
3829
3830
3831# https://docs.snowflake.com/en/sql-reference/functions/hll
3832# https://docs.aws.amazon.com/redshift/latest/dg/r_HLL_function.html
3833class Hll(AggFunc):
3834    arg_types = {"this": True, "expressions": False}
3835    is_var_len_args = True
3836
3837
3838class ApproxDistinct(AggFunc):
3839    arg_types = {"this": True, "accuracy": False}
3840    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
3841
3842
3843class Array(Func):
3844    arg_types = {"expressions": False}
3845    is_var_len_args = True
3846
3847
3848# https://docs.snowflake.com/en/sql-reference/functions/to_char
3849class ToChar(Func):
3850    arg_types = {"this": True, "format": False}
3851
3852
3853class GenerateSeries(Func):
3854    arg_types = {"start": True, "end": True, "step": False}
3855
3856
3857class ArrayAgg(AggFunc):
3858    pass
3859
3860
3861class ArrayAll(Func):
3862    arg_types = {"this": True, "expression": True}
3863
3864
3865class ArrayAny(Func):
3866    arg_types = {"this": True, "expression": True}
3867
3868
3869class ArrayConcat(Func):
3870    arg_types = {"this": True, "expressions": False}
3871    is_var_len_args = True
3872
3873
3874class ArrayContains(Binary, Func):
3875    pass
3876
3877
3878class ArrayContained(Binary):
3879    pass
3880
3881
3882class ArrayFilter(Func):
3883    arg_types = {"this": True, "expression": True}
3884    _sql_names = ["FILTER", "ARRAY_FILTER"]
3885
3886
3887class ArrayJoin(Func):
3888    arg_types = {"this": True, "expression": True, "null": False}
3889
3890
3891class ArraySize(Func):
3892    arg_types = {"this": True, "expression": False}
3893
3894
3895class ArraySort(Func):
3896    arg_types = {"this": True, "expression": False}
3897
3898
3899class ArraySum(Func):
3900    pass
3901
3902
3903class ArrayUnionAgg(AggFunc):
3904    pass
3905
3906
3907class Avg(AggFunc):
3908    pass
3909
3910
3911class AnyValue(AggFunc):
3912    pass
3913
3914
3915class Case(Func):
3916    arg_types = {"this": False, "ifs": True, "default": False}
3917
3918    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3919        instance = _maybe_copy(self, copy)
3920        instance.append(
3921            "ifs",
3922            If(
3923                this=maybe_parse(condition, copy=copy, **opts),
3924                true=maybe_parse(then, copy=copy, **opts),
3925            ),
3926        )
3927        return instance
3928
3929    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3930        instance = _maybe_copy(self, copy)
3931        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3932        return instance
3933
3934
3935class Cast(Func):
3936    arg_types = {"this": True, "to": True}
3937
3938    @property
3939    def name(self) -> str:
3940        return self.this.name
3941
3942    @property
3943    def to(self) -> DataType:
3944        return self.args["to"]
3945
3946    @property
3947    def output_name(self) -> str:
3948        return self.name
3949
3950    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3951        return self.to.is_type(*dtypes)
3952
3953
3954class CastToStrType(Func):
3955    arg_types = {"this": True, "expression": True}
3956
3957
3958class Collate(Binary):
3959    pass
3960
3961
3962class TryCast(Cast):
3963    pass
3964
3965
3966class Ceil(Func):
3967    arg_types = {"this": True, "decimals": False}
3968    _sql_names = ["CEIL", "CEILING"]
3969
3970
3971class Coalesce(Func):
3972    arg_types = {"this": True, "expressions": False}
3973    is_var_len_args = True
3974    _sql_names = ["COALESCE", "IFNULL", "NVL"]
3975
3976
3977class Concat(Func):
3978    arg_types = {"expressions": True}
3979    is_var_len_args = True
3980
3981
3982class SafeConcat(Concat):
3983    pass
3984
3985
3986class ConcatWs(Concat):
3987    _sql_names = ["CONCAT_WS"]
3988
3989
3990class Count(AggFunc):
3991    arg_types = {"this": False, "expressions": False}
3992    is_var_len_args = True
3993
3994
3995class CountIf(AggFunc):
3996    pass
3997
3998
3999class CurrentDate(Func):
4000    arg_types = {"this": False}
4001
4002
4003class CurrentDatetime(Func):
4004    arg_types = {"this": False}
4005
4006
4007class CurrentTime(Func):
4008    arg_types = {"this": False}
4009
4010
4011class CurrentTimestamp(Func):
4012    arg_types = {"this": False}
4013
4014
4015class CurrentUser(Func):
4016    arg_types = {"this": False}
4017
4018
4019class DateAdd(Func, TimeUnit):
4020    arg_types = {"this": True, "expression": True, "unit": False}
4021
4022
4023class DateSub(Func, TimeUnit):
4024    arg_types = {"this": True, "expression": True, "unit": False}
4025
4026
4027class DateDiff(Func, TimeUnit):
4028    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4029    arg_types = {"this": True, "expression": True, "unit": False}
4030
4031
4032class DateTrunc(Func):
4033    arg_types = {"unit": True, "this": True, "zone": False}
4034
4035
4036class DatetimeAdd(Func, TimeUnit):
4037    arg_types = {"this": True, "expression": True, "unit": False}
4038
4039
4040class DatetimeSub(Func, TimeUnit):
4041    arg_types = {"this": True, "expression": True, "unit": False}
4042
4043
4044class DatetimeDiff(Func, TimeUnit):
4045    arg_types = {"this": True, "expression": True, "unit": False}
4046
4047
4048class DatetimeTrunc(Func, TimeUnit):
4049    arg_types = {"this": True, "unit": True, "zone": False}
4050
4051
4052class DayOfWeek(Func):
4053    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
4054
4055
4056class DayOfMonth(Func):
4057    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
4058
4059
4060class DayOfYear(Func):
4061    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
4062
4063
4064class WeekOfYear(Func):
4065    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
4066
4067
4068class LastDateOfMonth(Func):
4069    pass
4070
4071
4072class Extract(Func):
4073    arg_types = {"this": True, "expression": True}
4074
4075
4076class TimestampAdd(Func, TimeUnit):
4077    arg_types = {"this": True, "expression": True, "unit": False}
4078
4079
4080class TimestampSub(Func, TimeUnit):
4081    arg_types = {"this": True, "expression": True, "unit": False}
4082
4083
4084class TimestampDiff(Func, TimeUnit):
4085    arg_types = {"this": True, "expression": True, "unit": False}
4086
4087
4088class TimestampTrunc(Func, TimeUnit):
4089    arg_types = {"this": True, "unit": True, "zone": False}
4090
4091
4092class TimeAdd(Func, TimeUnit):
4093    arg_types = {"this": True, "expression": True, "unit": False}
4094
4095
4096class TimeSub(Func, TimeUnit):
4097    arg_types = {"this": True, "expression": True, "unit": False}
4098
4099
4100class TimeDiff(Func, TimeUnit):
4101    arg_types = {"this": True, "expression": True, "unit": False}
4102
4103
4104class TimeTrunc(Func, TimeUnit):
4105    arg_types = {"this": True, "unit": True, "zone": False}
4106
4107
4108class DateFromParts(Func):
4109    _sql_names = ["DATEFROMPARTS"]
4110    arg_types = {"year": True, "month": True, "day": True}
4111
4112
4113class DateStrToDate(Func):
4114    pass
4115
4116
4117class DateToDateStr(Func):
4118    pass
4119
4120
4121class DateToDi(Func):
4122    pass
4123
4124
4125class Date(Func):
4126    arg_types = {"expressions": True}
4127    is_var_len_args = True
4128
4129
4130class Day(Func):
4131    pass
4132
4133
4134class Decode(Func):
4135    arg_types = {"this": True, "charset": True, "replace": False}
4136
4137
4138class DiToDate(Func):
4139    pass
4140
4141
4142class Encode(Func):
4143    arg_types = {"this": True, "charset": True}
4144
4145
4146class Exp(Func):
4147    pass
4148
4149
4150class Explode(Func):
4151    pass
4152
4153
4154class Floor(Func):
4155    arg_types = {"this": True, "decimals": False}
4156
4157
4158class FromBase64(Func):
4159    pass
4160
4161
4162class ToBase64(Func):
4163    pass
4164
4165
4166class Greatest(Func):
4167    arg_types = {"this": True, "expressions": False}
4168    is_var_len_args = True
4169
4170
4171class GroupConcat(Func):
4172    arg_types = {"this": True, "separator": False}
4173
4174
4175class Hex(Func):
4176    pass
4177
4178
4179class If(Func):
4180    arg_types = {"this": True, "true": True, "false": False}
4181
4182
4183class Initcap(Func):
4184    arg_types = {"this": True, "expression": False}
4185
4186
4187class JSONKeyValue(Expression):
4188    arg_types = {"this": True, "expression": True}
4189
4190
4191class JSONObject(Func):
4192    arg_types = {
4193        "expressions": False,
4194        "null_handling": False,
4195        "unique_keys": False,
4196        "return_type": False,
4197        "format_json": False,
4198        "encoding": False,
4199    }
4200
4201
4202class OpenJSONColumnDef(Expression):
4203    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
4204
4205
4206class OpenJSON(Func):
4207    arg_types = {"this": True, "path": False, "expressions": False}
4208
4209
4210class JSONBContains(Binary):
4211    _sql_names = ["JSONB_CONTAINS"]
4212
4213
4214class JSONExtract(Binary, Func):
4215    _sql_names = ["JSON_EXTRACT"]
4216
4217
4218class JSONExtractScalar(JSONExtract):
4219    _sql_names = ["JSON_EXTRACT_SCALAR"]
4220
4221
4222class JSONBExtract(JSONExtract):
4223    _sql_names = ["JSONB_EXTRACT"]
4224
4225
4226class JSONBExtractScalar(JSONExtract):
4227    _sql_names = ["JSONB_EXTRACT_SCALAR"]
4228
4229
4230class JSONFormat(Func):
4231    arg_types = {"this": False, "options": False}
4232    _sql_names = ["JSON_FORMAT"]
4233
4234
4235class Least(Func):
4236    arg_types = {"expressions": False}
4237    is_var_len_args = True
4238
4239
4240class Left(Func):
4241    arg_types = {"this": True, "expression": True}
4242
4243
4244class Right(Func):
4245    arg_types = {"this": True, "expression": True}
4246
4247
4248class Length(Func):
4249    _sql_names = ["LENGTH", "LEN"]
4250
4251
4252class Levenshtein(Func):
4253    arg_types = {
4254        "this": True,
4255        "expression": False,
4256        "ins_cost": False,
4257        "del_cost": False,
4258        "sub_cost": False,
4259    }
4260
4261
4262class Ln(Func):
4263    pass
4264
4265
4266class Log(Func):
4267    arg_types = {"this": True, "expression": False}
4268
4269
4270class Log2(Func):
4271    pass
4272
4273
4274class Log10(Func):
4275    pass
4276
4277
4278class LogicalOr(AggFunc):
4279    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
4280
4281
4282class LogicalAnd(AggFunc):
4283    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
4284
4285
4286class Lower(Func):
4287    _sql_names = ["LOWER", "LCASE"]
4288
4289
4290class Map(Func):
4291    arg_types = {"keys": False, "values": False}
4292
4293
4294class StarMap(Func):
4295    pass
4296
4297
4298class VarMap(Func):
4299    arg_types = {"keys": True, "values": True}
4300    is_var_len_args = True
4301
4302    @property
4303    def keys(self) -> t.List[Expression]:
4304        return self.args["keys"].expressions
4305
4306    @property
4307    def values(self) -> t.List[Expression]:
4308        return self.args["values"].expressions
4309
4310
4311# https://dev.mysql.com/doc/refman/8.0/en/fulltext-search.html
4312class MatchAgainst(Func):
4313    arg_types = {"this": True, "expressions": True, "modifier": False}
4314
4315
4316class Max(AggFunc):
4317    arg_types = {"this": True, "expressions": False}
4318    is_var_len_args = True
4319
4320
4321class MD5(Func):
4322    _sql_names = ["MD5"]
4323
4324
4325class Min(AggFunc):
4326    arg_types = {"this": True, "expressions": False}
4327    is_var_len_args = True
4328
4329
4330class Month(Func):
4331    pass
4332
4333
4334class Nvl2(Func):
4335    arg_types = {"this": True, "true": True, "false": False}
4336
4337
4338class Posexplode(Func):
4339    pass
4340
4341
4342class Pow(Binary, Func):
4343    _sql_names = ["POWER", "POW"]
4344
4345
4346class PercentileCont(AggFunc):
4347    arg_types = {"this": True, "expression": False}
4348
4349
4350class PercentileDisc(AggFunc):
4351    arg_types = {"this": True, "expression": False}
4352
4353
4354class Quantile(AggFunc):
4355    arg_types = {"this": True, "quantile": True}
4356
4357
4358class ApproxQuantile(Quantile):
4359    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
4360
4361
4362class RangeN(Func):
4363    arg_types = {"this": True, "expressions": True, "each": False}
4364
4365
4366class ReadCSV(Func):
4367    _sql_names = ["READ_CSV"]
4368    is_var_len_args = True
4369    arg_types = {"this": True, "expressions": False}
4370
4371
4372class Reduce(Func):
4373    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
4374
4375
4376class RegexpExtract(Func):
4377    arg_types = {
4378        "this": True,
4379        "expression": True,
4380        "position": False,
4381        "occurrence": False,
4382        "group": False,
4383    }
4384
4385
4386class RegexpLike(Func):
4387    arg_types = {"this": True, "expression": True, "flag": False}
4388
4389
4390class RegexpILike(Func):
4391    arg_types = {"this": True, "expression": True, "flag": False}
4392
4393
4394# https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.functions.split.html
4395# limit is the number of times a pattern is applied
4396class RegexpSplit(Func):
4397    arg_types = {"this": True, "expression": True, "limit": False}
4398
4399
4400class Repeat(Func):
4401    arg_types = {"this": True, "times": True}
4402
4403
4404class Round(Func):
4405    arg_types = {"this": True, "decimals": False}
4406
4407
4408class RowNumber(Func):
4409    arg_types: t.Dict[str, t.Any] = {}
4410
4411
4412class SafeDivide(Func):
4413    arg_types = {"this": True, "expression": True}
4414
4415
4416class SetAgg(AggFunc):
4417    pass
4418
4419
4420class SHA(Func):
4421    _sql_names = ["SHA", "SHA1"]
4422
4423
4424class SHA2(Func):
4425    _sql_names = ["SHA2"]
4426    arg_types = {"this": True, "length": False}
4427
4428
4429class SortArray(Func):
4430    arg_types = {"this": True, "asc": False}
4431
4432
4433class Split(Func):
4434    arg_types = {"this": True, "expression": True, "limit": False}
4435
4436
4437# Start may be omitted in the case of postgres
4438# https://www.postgresql.org/docs/9.1/functions-string.html @ Table 9-6
4439class Substring(Func):
4440    arg_types = {"this": True, "start": False, "length": False}
4441
4442
4443class StandardHash(Func):
4444    arg_types = {"this": True, "expression": False}
4445
4446
4447class StrPosition(Func):
4448    arg_types = {
4449        "this": True,
4450        "substr": True,
4451        "position": False,
4452        "instance": False,
4453    }
4454
4455
4456class StrToDate(Func):
4457    arg_types = {"this": True, "format": True}
4458
4459
4460class StrToTime(Func):
4461    arg_types = {"this": True, "format": True}
4462
4463
4464# Spark allows unix_timestamp()
4465# https://spark.apache.org/docs/3.1.3/api/python/reference/api/pyspark.sql.functions.unix_timestamp.html
4466class StrToUnix(Func):
4467    arg_types = {"this": False, "format": False}
4468
4469
4470class NumberToStr(Func):
4471    arg_types = {"this": True, "format": True}
4472
4473
4474class FromBase(Func):
4475    arg_types = {"this": True, "expression": True}
4476
4477
4478class Struct(Func):
4479    arg_types = {"expressions": True}
4480    is_var_len_args = True
4481
4482
4483class StructExtract(Func):
4484    arg_types = {"this": True, "expression": True}
4485
4486
4487class Sum(AggFunc):
4488    pass
4489
4490
4491class Sqrt(Func):
4492    pass
4493
4494
4495class Stddev(AggFunc):
4496    pass
4497
4498
4499class StddevPop(AggFunc):
4500    pass
4501
4502
4503class StddevSamp(AggFunc):
4504    pass
4505
4506
4507class TimeToStr(Func):
4508    arg_types = {"this": True, "format": True}
4509
4510
4511class TimeToTimeStr(Func):
4512    pass
4513
4514
4515class TimeToUnix(Func):
4516    pass
4517
4518
4519class TimeStrToDate(Func):
4520    pass
4521
4522
4523class TimeStrToTime(Func):
4524    pass
4525
4526
4527class TimeStrToUnix(Func):
4528    pass
4529
4530
4531class Trim(Func):
4532    arg_types = {
4533        "this": True,
4534        "expression": False,
4535        "position": False,
4536        "collation": False,
4537    }
4538
4539
4540class TsOrDsAdd(Func, TimeUnit):
4541    arg_types = {"this": True, "expression": True, "unit": False}
4542
4543
4544class TsOrDsToDateStr(Func):
4545    pass
4546
4547
4548class TsOrDsToDate(Func):
4549    arg_types = {"this": True, "format": False}
4550
4551
4552class TsOrDiToDi(Func):
4553    pass
4554
4555
4556class Unhex(Func):
4557    pass
4558
4559
4560class UnixToStr(Func):
4561    arg_types = {"this": True, "format": False}
4562
4563
4564# https://prestodb.io/docs/current/functions/datetime.html
4565# presto has weird zone/hours/minutes
4566class UnixToTime(Func):
4567    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4568
4569    SECONDS = Literal.string("seconds")
4570    MILLIS = Literal.string("millis")
4571    MICROS = Literal.string("micros")
4572
4573
4574class UnixToTimeStr(Func):
4575    pass
4576
4577
4578class Upper(Func):
4579    _sql_names = ["UPPER", "UCASE"]
4580
4581
4582class Variance(AggFunc):
4583    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
4584
4585
4586class VariancePop(AggFunc):
4587    _sql_names = ["VARIANCE_POP", "VAR_POP"]
4588
4589
4590class Week(Func):
4591    arg_types = {"this": True, "mode": False}
4592
4593
4594class XMLTable(Func):
4595    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
4596
4597
4598class Year(Func):
4599    pass
4600
4601
4602class Use(Expression):
4603    arg_types = {"this": True, "kind": False}
4604
4605
4606class Merge(Expression):
4607    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
4608
4609
4610class When(Func):
4611    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
4612
4613
4614# https://docs.oracle.com/javadb/10.8.3.0/ref/rrefsqljnextvaluefor.html
4615# https://learn.microsoft.com/en-us/sql/t-sql/functions/next-value-for-transact-sql?view=sql-server-ver16
4616class NextValueFor(Func):
4617    arg_types = {"this": True, "order": False}
4618
4619
4620def _norm_arg(arg):
4621    return arg.lower() if type(arg) is str else arg
4622
4623
4624ALL_FUNCTIONS = subclasses(__name__, Func, (AggFunc, Anonymous, Func))
4625
4626
4627# Helpers
4628@t.overload
4629def maybe_parse(
4630    sql_or_expression: ExpOrStr,
4631    *,
4632    into: t.Type[E],
4633    dialect: DialectType = None,
4634    prefix: t.Optional[str] = None,
4635    copy: bool = False,
4636    **opts,
4637) -> E:
4638    ...
4639
4640
4641@t.overload
4642def maybe_parse(
4643    sql_or_expression: str | E,
4644    *,
4645    into: t.Optional[IntoType] = None,
4646    dialect: DialectType = None,
4647    prefix: t.Optional[str] = None,
4648    copy: bool = False,
4649    **opts,
4650) -> E:
4651    ...
4652
4653
4654def maybe_parse(
4655    sql_or_expression: ExpOrStr,
4656    *,
4657    into: t.Optional[IntoType] = None,
4658    dialect: DialectType = None,
4659    prefix: t.Optional[str] = None,
4660    copy: bool = False,
4661    **opts,
4662) -> Expression:
4663    """Gracefully handle a possible string or expression.
4664
4665    Example:
4666        >>> maybe_parse("1")
4667        (LITERAL this: 1, is_string: False)
4668        >>> maybe_parse(to_identifier("x"))
4669        (IDENTIFIER this: x, quoted: False)
4670
4671    Args:
4672        sql_or_expression: the SQL code string or an expression
4673        into: the SQLGlot Expression to parse into
4674        dialect: the dialect used to parse the input expressions (in the case that an
4675            input expression is a SQL string).
4676        prefix: a string to prefix the sql with before it gets parsed
4677            (automatically includes a space)
4678        copy: whether or not to copy the expression.
4679        **opts: other options to use to parse the input expressions (again, in the case
4680            that an input expression is a SQL string).
4681
4682    Returns:
4683        Expression: the parsed or given expression.
4684    """
4685    if isinstance(sql_or_expression, Expression):
4686        if copy:
4687            return sql_or_expression.copy()
4688        return sql_or_expression
4689
4690    if sql_or_expression is None:
4691        raise ParseError(f"SQL cannot be None")
4692
4693    import sqlglot
4694
4695    sql = str(sql_or_expression)
4696    if prefix:
4697        sql = f"{prefix} {sql}"
4698
4699    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)
4700
4701
4702def _maybe_copy(instance: E, copy: bool = True) -> E:
4703    return instance.copy() if copy else instance
4704
4705
4706def _is_wrong_expression(expression, into):
4707    return isinstance(expression, Expression) and not isinstance(expression, into)
4708
4709
4710def _apply_builder(
4711    expression,
4712    instance,
4713    arg,
4714    copy=True,
4715    prefix=None,
4716    into=None,
4717    dialect=None,
4718    **opts,
4719):
4720    if _is_wrong_expression(expression, into):
4721        expression = into(this=expression)
4722    instance = _maybe_copy(instance, copy)
4723    expression = maybe_parse(
4724        sql_or_expression=expression,
4725        prefix=prefix,
4726        into=into,
4727        dialect=dialect,
4728        **opts,
4729    )
4730    instance.set(arg, expression)
4731    return instance
4732
4733
4734def _apply_child_list_builder(
4735    *expressions,
4736    instance,
4737    arg,
4738    append=True,
4739    copy=True,
4740    prefix=None,
4741    into=None,
4742    dialect=None,
4743    properties=None,
4744    **opts,
4745):
4746    instance = _maybe_copy(instance, copy)
4747    parsed = []
4748    for expression in expressions:
4749        if expression is not None:
4750            if _is_wrong_expression(expression, into):
4751                expression = into(expressions=[expression])
4752
4753            expression = maybe_parse(
4754                expression,
4755                into=into,
4756                dialect=dialect,
4757                prefix=prefix,
4758                **opts,
4759            )
4760            parsed.extend(expression.expressions)
4761
4762    existing = instance.args.get(arg)
4763    if append and existing:
4764        parsed = existing.expressions + parsed
4765
4766    child = into(expressions=parsed)
4767    for k, v in (properties or {}).items():
4768        child.set(k, v)
4769    instance.set(arg, child)
4770
4771    return instance
4772
4773
4774def _apply_list_builder(
4775    *expressions,
4776    instance,
4777    arg,
4778    append=True,
4779    copy=True,
4780    prefix=None,
4781    into=None,
4782    dialect=None,
4783    **opts,
4784):
4785    inst = _maybe_copy(instance, copy)
4786
4787    expressions = [
4788        maybe_parse(
4789            sql_or_expression=expression,
4790            into=into,
4791            prefix=prefix,
4792            dialect=dialect,
4793            **opts,
4794        )
4795        for expression in expressions
4796        if expression is not None
4797    ]
4798
4799    existing_expressions = inst.args.get(arg)
4800    if append and existing_expressions:
4801        expressions = existing_expressions + expressions
4802
4803    inst.set(arg, expressions)
4804    return inst
4805
4806
4807def _apply_conjunction_builder(
4808    *expressions,
4809    instance,
4810    arg,
4811    into=None,
4812    append=True,
4813    copy=True,
4814    dialect=None,
4815    **opts,
4816):
4817    expressions = [exp for exp in expressions if exp is not None and exp != ""]
4818    if not expressions:
4819        return instance
4820
4821    inst = _maybe_copy(instance, copy)
4822
4823    existing = inst.args.get(arg)
4824    if append and existing is not None:
4825        expressions = [existing.this if into else existing] + list(expressions)
4826
4827    node = and_(*expressions, dialect=dialect, copy=copy, **opts)
4828
4829    inst.set(arg, into(this=node) if into else node)
4830    return inst
4831
4832
4833def _apply_cte_builder(
4834    instance: E,
4835    alias: ExpOrStr,
4836    as_: ExpOrStr,
4837    recursive: t.Optional[bool] = None,
4838    append: bool = True,
4839    dialect: DialectType = None,
4840    copy: bool = True,
4841    **opts,
4842) -> E:
4843    alias_expression = maybe_parse(alias, dialect=dialect, into=TableAlias, **opts)
4844    as_expression = maybe_parse(as_, dialect=dialect, **opts)
4845    cte = CTE(this=as_expression, alias=alias_expression)
4846    return _apply_child_list_builder(
4847        cte,
4848        instance=instance,
4849        arg="with",
4850        append=append,
4851        copy=copy,
4852        into=With,
4853        properties={"recursive": recursive or False},
4854    )
4855
4856
4857def _combine(
4858    expressions: t.Sequence[t.Optional[ExpOrStr]],
4859    operator: t.Type[Connector],
4860    dialect: DialectType = None,
4861    copy: bool = True,
4862    **opts,
4863) -> Expression:
4864    conditions = [
4865        condition(expression, dialect=dialect, copy=copy, **opts)
4866        for expression in expressions
4867        if expression is not None
4868    ]
4869
4870    this, *rest = conditions
4871    if rest:
4872        this = _wrap(this, Connector)
4873    for expression in rest:
4874        this = operator(this=this, expression=_wrap(expression, Connector))
4875
4876    return this
4877
4878
4879def _wrap(expression: E, kind: t.Type[Expression]) -> E | Paren:
4880    return Paren(this=expression) if isinstance(expression, kind) else expression
4881
4882
4883def union(
4884    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4885) -> Union:
4886    """
4887    Initializes a syntax tree from one UNION expression.
4888
4889    Example:
4890        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4891        'SELECT * FROM foo UNION SELECT * FROM bla'
4892
4893    Args:
4894        left: the SQL code string corresponding to the left-hand side.
4895            If an `Expression` instance is passed, it will be used as-is.
4896        right: the SQL code string corresponding to the right-hand side.
4897            If an `Expression` instance is passed, it will be used as-is.
4898        distinct: set the DISTINCT flag if and only if this is true.
4899        dialect: the dialect used to parse the input expression.
4900        opts: other options to use to parse the input expressions.
4901
4902    Returns:
4903        The new Union instance.
4904    """
4905    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4906    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4907
4908    return Union(this=left, expression=right, distinct=distinct)
4909
4910
4911def intersect(
4912    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4913) -> Intersect:
4914    """
4915    Initializes a syntax tree from one INTERSECT expression.
4916
4917    Example:
4918        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4919        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4920
4921    Args:
4922        left: the SQL code string corresponding to the left-hand side.
4923            If an `Expression` instance is passed, it will be used as-is.
4924        right: the SQL code string corresponding to the right-hand side.
4925            If an `Expression` instance is passed, it will be used as-is.
4926        distinct: set the DISTINCT flag if and only if this is true.
4927        dialect: the dialect used to parse the input expression.
4928        opts: other options to use to parse the input expressions.
4929
4930    Returns:
4931        The new Intersect instance.
4932    """
4933    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4934    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4935
4936    return Intersect(this=left, expression=right, distinct=distinct)
4937
4938
4939def except_(
4940    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4941) -> Except:
4942    """
4943    Initializes a syntax tree from one EXCEPT expression.
4944
4945    Example:
4946        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4947        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4948
4949    Args:
4950        left: the SQL code string corresponding to the left-hand side.
4951            If an `Expression` instance is passed, it will be used as-is.
4952        right: the SQL code string corresponding to the right-hand side.
4953            If an `Expression` instance is passed, it will be used as-is.
4954        distinct: set the DISTINCT flag if and only if this is true.
4955        dialect: the dialect used to parse the input expression.
4956        opts: other options to use to parse the input expressions.
4957
4958    Returns:
4959        The new Except instance.
4960    """
4961    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4962    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4963
4964    return Except(this=left, expression=right, distinct=distinct)
4965
4966
4967def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4968    """
4969    Initializes a syntax tree from one or multiple SELECT expressions.
4970
4971    Example:
4972        >>> select("col1", "col2").from_("tbl").sql()
4973        'SELECT col1, col2 FROM tbl'
4974
4975    Args:
4976        *expressions: the SQL code string to parse as the expressions of a
4977            SELECT statement. If an Expression instance is passed, this is used as-is.
4978        dialect: the dialect used to parse the input expressions (in the case that an
4979            input expression is a SQL string).
4980        **opts: other options to use to parse the input expressions (again, in the case
4981            that an input expression is a SQL string).
4982
4983    Returns:
4984        Select: the syntax tree for the SELECT statement.
4985    """
4986    return Select().select(*expressions, dialect=dialect, **opts)
4987
4988
4989def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4990    """
4991    Initializes a syntax tree from a FROM expression.
4992
4993    Example:
4994        >>> from_("tbl").select("col1", "col2").sql()
4995        'SELECT col1, col2 FROM tbl'
4996
4997    Args:
4998        *expression: the SQL code string to parse as the FROM expressions of a
4999            SELECT statement. If an Expression instance is passed, this is used as-is.
5000        dialect: the dialect used to parse the input expression (in the case that the
5001            input expression is a SQL string).
5002        **opts: other options to use to parse the input expressions (again, in the case
5003            that the input expression is a SQL string).
5004
5005    Returns:
5006        Select: the syntax tree for the SELECT statement.
5007    """
5008    return Select().from_(expression, dialect=dialect, **opts)
5009
5010
5011def update(
5012    table: str | Table,
5013    properties: dict,
5014    where: t.Optional[ExpOrStr] = None,
5015    from_: t.Optional[ExpOrStr] = None,
5016    dialect: DialectType = None,
5017    **opts,
5018) -> Update:
5019    """
5020    Creates an update statement.
5021
5022    Example:
5023        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5024        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5025
5026    Args:
5027        *properties: dictionary of properties to set which are
5028            auto converted to sql objects eg None -> NULL
5029        where: sql conditional parsed into a WHERE statement
5030        from_: sql statement parsed into a FROM statement
5031        dialect: the dialect used to parse the input expressions.
5032        **opts: other options to use to parse the input expressions.
5033
5034    Returns:
5035        Update: the syntax tree for the UPDATE statement.
5036    """
5037    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5038    update_expr.set(
5039        "expressions",
5040        [
5041            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5042            for k, v in properties.items()
5043        ],
5044    )
5045    if from_:
5046        update_expr.set(
5047            "from",
5048            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5049        )
5050    if isinstance(where, Condition):
5051        where = Where(this=where)
5052    if where:
5053        update_expr.set(
5054            "where",
5055            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5056        )
5057    return update_expr
5058
5059
5060def delete(
5061    table: ExpOrStr,
5062    where: t.Optional[ExpOrStr] = None,
5063    returning: t.Optional[ExpOrStr] = None,
5064    dialect: DialectType = None,
5065    **opts,
5066) -> Delete:
5067    """
5068    Builds a delete statement.
5069
5070    Example:
5071        >>> delete("my_table", where="id > 1").sql()
5072        'DELETE FROM my_table WHERE id > 1'
5073
5074    Args:
5075        where: sql conditional parsed into a WHERE statement
5076        returning: sql conditional parsed into a RETURNING statement
5077        dialect: the dialect used to parse the input expressions.
5078        **opts: other options to use to parse the input expressions.
5079
5080    Returns:
5081        Delete: the syntax tree for the DELETE statement.
5082    """
5083    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5084    if where:
5085        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5086    if returning:
5087        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5088    return delete_expr
5089
5090
5091def insert(
5092    expression: ExpOrStr,
5093    into: ExpOrStr,
5094    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5095    overwrite: t.Optional[bool] = None,
5096    dialect: DialectType = None,
5097    copy: bool = True,
5098    **opts,
5099) -> Insert:
5100    """
5101    Builds an INSERT statement.
5102
5103    Example:
5104        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5105        'INSERT INTO tbl VALUES (1, 2, 3)'
5106
5107    Args:
5108        expression: the sql string or expression of the INSERT statement
5109        into: the tbl to insert data to.
5110        columns: optionally the table's column names.
5111        overwrite: whether to INSERT OVERWRITE or not.
5112        dialect: the dialect used to parse the input expressions.
5113        copy: whether or not to copy the expression.
5114        **opts: other options to use to parse the input expressions.
5115
5116    Returns:
5117        Insert: the syntax tree for the INSERT statement.
5118    """
5119    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5120    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5121
5122    if columns:
5123        this = _apply_list_builder(
5124            *columns,
5125            instance=Schema(this=this),
5126            arg="expressions",
5127            into=Identifier,
5128            copy=False,
5129            dialect=dialect,
5130            **opts,
5131        )
5132
5133    return Insert(this=this, expression=expr, overwrite=overwrite)
5134
5135
5136def condition(
5137    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5138) -> Condition:
5139    """
5140    Initialize a logical condition expression.
5141
5142    Example:
5143        >>> condition("x=1").sql()
5144        'x = 1'
5145
5146        This is helpful for composing larger logical syntax trees:
5147        >>> where = condition("x=1")
5148        >>> where = where.and_("y=1")
5149        >>> Select().from_("tbl").select("*").where(where).sql()
5150        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5151
5152    Args:
5153        *expression: the SQL code string to parse.
5154            If an Expression instance is passed, this is used as-is.
5155        dialect: the dialect used to parse the input expression (in the case that the
5156            input expression is a SQL string).
5157        copy: Whether or not to copy `expression` (only applies to expressions).
5158        **opts: other options to use to parse the input expressions (again, in the case
5159            that the input expression is a SQL string).
5160
5161    Returns:
5162        The new Condition instance
5163    """
5164    return maybe_parse(
5165        expression,
5166        into=Condition,
5167        dialect=dialect,
5168        copy=copy,
5169        **opts,
5170    )
5171
5172
5173def and_(
5174    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5175) -> Condition:
5176    """
5177    Combine multiple conditions with an AND logical operator.
5178
5179    Example:
5180        >>> and_("x=1", and_("y=1", "z=1")).sql()
5181        'x = 1 AND (y = 1 AND z = 1)'
5182
5183    Args:
5184        *expressions: the SQL code strings to parse.
5185            If an Expression instance is passed, this is used as-is.
5186        dialect: the dialect used to parse the input expression.
5187        copy: whether or not to copy `expressions` (only applies to Expressions).
5188        **opts: other options to use to parse the input expressions.
5189
5190    Returns:
5191        And: the new condition
5192    """
5193    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))
5194
5195
5196def or_(
5197    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5198) -> Condition:
5199    """
5200    Combine multiple conditions with an OR logical operator.
5201
5202    Example:
5203        >>> or_("x=1", or_("y=1", "z=1")).sql()
5204        'x = 1 OR (y = 1 OR z = 1)'
5205
5206    Args:
5207        *expressions: the SQL code strings to parse.
5208            If an Expression instance is passed, this is used as-is.
5209        dialect: the dialect used to parse the input expression.
5210        copy: whether or not to copy `expressions` (only applies to Expressions).
5211        **opts: other options to use to parse the input expressions.
5212
5213    Returns:
5214        Or: the new condition
5215    """
5216    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))
5217
5218
5219def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5220    """
5221    Wrap a condition with a NOT operator.
5222
5223    Example:
5224        >>> not_("this_suit='black'").sql()
5225        "NOT this_suit = 'black'"
5226
5227    Args:
5228        expression: the SQL code string to parse.
5229            If an Expression instance is passed, this is used as-is.
5230        dialect: the dialect used to parse the input expression.
5231        copy: whether to copy the expression or not.
5232        **opts: other options to use to parse the input expressions.
5233
5234    Returns:
5235        The new condition.
5236    """
5237    this = condition(
5238        expression,
5239        dialect=dialect,
5240        copy=copy,
5241        **opts,
5242    )
5243    return Not(this=_wrap(this, Connector))
5244
5245
5246def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5247    """
5248    Wrap an expression in parentheses.
5249
5250    Example:
5251        >>> paren("5 + 3").sql()
5252        '(5 + 3)'
5253
5254    Args:
5255        expression: the SQL code string to parse.
5256            If an Expression instance is passed, this is used as-is.
5257        copy: whether to copy the expression or not.
5258
5259    Returns:
5260        The wrapped expression.
5261    """
5262    return Paren(this=maybe_parse(expression, copy=copy))
5263
5264
5265SAFE_IDENTIFIER_RE = re.compile(r"^[_a-zA-Z][\w]*$")
5266
5267
5268@t.overload
5269def to_identifier(name: None, quoted: t.Optional[bool] = None, copy: bool = True) -> None:
5270    ...
5271
5272
5273@t.overload
5274def to_identifier(
5275    name: str | Identifier, quoted: t.Optional[bool] = None, copy: bool = True
5276) -> Identifier:
5277    ...
5278
5279
5280def to_identifier(name, quoted=None, copy=True):
5281    """Builds an identifier.
5282
5283    Args:
5284        name: The name to turn into an identifier.
5285        quoted: Whether or not force quote the identifier.
5286        copy: Whether or not to copy a passed in Identefier node.
5287
5288    Returns:
5289        The identifier ast node.
5290    """
5291
5292    if name is None:
5293        return None
5294
5295    if isinstance(name, Identifier):
5296        identifier = _maybe_copy(name, copy)
5297    elif isinstance(name, str):
5298        identifier = Identifier(
5299            this=name,
5300            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5301        )
5302    else:
5303        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5304    return identifier
5305
5306
5307INTERVAL_STRING_RE = re.compile(r"\s*([0-9]+)\s*([a-zA-Z]+)\s*")
5308
5309
5310def to_interval(interval: str | Literal) -> Interval:
5311    """Builds an interval expression from a string like '1 day' or '5 months'."""
5312    if isinstance(interval, Literal):
5313        if not interval.is_string:
5314            raise ValueError("Invalid interval string.")
5315
5316        interval = interval.this
5317
5318    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5319
5320    if not interval_parts:
5321        raise ValueError("Invalid interval string.")
5322
5323    return Interval(
5324        this=Literal.string(interval_parts.group(1)),
5325        unit=Var(this=interval_parts.group(2)),
5326    )
5327
5328
5329@t.overload
5330def to_table(sql_path: str | Table, **kwargs) -> Table:
5331    ...
5332
5333
5334@t.overload
5335def to_table(sql_path: None, **kwargs) -> None:
5336    ...
5337
5338
5339def to_table(
5340    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5341) -> t.Optional[Table]:
5342    """
5343    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5344    If a table is passed in then that table is returned.
5345
5346    Args:
5347        sql_path: a `[catalog].[schema].[table]` string.
5348        dialect: the source dialect according to which the table name will be parsed.
5349        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5350
5351    Returns:
5352        A table expression.
5353    """
5354    if sql_path is None or isinstance(sql_path, Table):
5355        return sql_path
5356    if not isinstance(sql_path, str):
5357        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5358
5359    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5360    if table:
5361        for k, v in kwargs.items():
5362            table.set(k, v)
5363
5364    return table
5365
5366
5367def to_column(sql_path: str | Column, **kwargs) -> Column:
5368    """
5369    Create a column from a `[table].[column]` sql path. Schema is optional.
5370
5371    If a column is passed in then that column is returned.
5372
5373    Args:
5374        sql_path: `[table].[column]` string
5375    Returns:
5376        Table: A column expression
5377    """
5378    if sql_path is None or isinstance(sql_path, Column):
5379        return sql_path
5380    if not isinstance(sql_path, str):
5381        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5382    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore
5383
5384
5385def alias_(
5386    expression: ExpOrStr,
5387    alias: str | Identifier,
5388    table: bool | t.Sequence[str | Identifier] = False,
5389    quoted: t.Optional[bool] = None,
5390    dialect: DialectType = None,
5391    copy: bool = True,
5392    **opts,
5393):
5394    """Create an Alias expression.
5395
5396    Example:
5397        >>> alias_('foo', 'bar').sql()
5398        'foo AS bar'
5399
5400        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5401        '(SELECT 1, 2) AS bar(a, b)'
5402
5403    Args:
5404        expression: the SQL code strings to parse.
5405            If an Expression instance is passed, this is used as-is.
5406        alias: the alias name to use. If the name has
5407            special characters it is quoted.
5408        table: Whether or not to create a table alias, can also be a list of columns.
5409        quoted: whether or not to quote the alias
5410        dialect: the dialect used to parse the input expression.
5411        copy: Whether or not to copy the expression.
5412        **opts: other options to use to parse the input expressions.
5413
5414    Returns:
5415        Alias: the aliased expression
5416    """
5417    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5418    alias = to_identifier(alias, quoted=quoted)
5419
5420    if table:
5421        table_alias = TableAlias(this=alias)
5422        exp.set("alias", table_alias)
5423
5424        if not isinstance(table, bool):
5425            for column in table:
5426                table_alias.append("columns", to_identifier(column, quoted=quoted))
5427
5428        return exp
5429
5430    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5431    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5432    # for the complete Window expression.
5433    #
5434    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5435
5436    if "alias" in exp.arg_types and not isinstance(exp, Window):
5437        exp.set("alias", alias)
5438        return exp
5439    return Alias(this=exp, alias=alias)
5440
5441
5442def subquery(
5443    expression: ExpOrStr,
5444    alias: t.Optional[Identifier | str] = None,
5445    dialect: DialectType = None,
5446    **opts,
5447) -> Select:
5448    """
5449    Build a subquery expression.
5450
5451    Example:
5452        >>> subquery('select x from tbl', 'bar').select('x').sql()
5453        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5454
5455    Args:
5456        expression: the SQL code strings to parse.
5457            If an Expression instance is passed, this is used as-is.
5458        alias: the alias name to use.
5459        dialect: the dialect used to parse the input expression.
5460        **opts: other options to use to parse the input expressions.
5461
5462    Returns:
5463        A new Select instance with the subquery expression included.
5464    """
5465
5466    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5467    return Select().from_(expression, dialect=dialect, **opts)
5468
5469
5470def column(
5471    col: str | Identifier,
5472    table: t.Optional[str | Identifier] = None,
5473    db: t.Optional[str | Identifier] = None,
5474    catalog: t.Optional[str | Identifier] = None,
5475    quoted: t.Optional[bool] = None,
5476) -> Column:
5477    """
5478    Build a Column.
5479
5480    Args:
5481        col: Column name.
5482        table: Table name.
5483        db: Database name.
5484        catalog: Catalog name.
5485        quoted: Whether to force quotes on the column's identifiers.
5486
5487    Returns:
5488        The new Column instance.
5489    """
5490    return Column(
5491        this=to_identifier(col, quoted=quoted),
5492        table=to_identifier(table, quoted=quoted),
5493        db=to_identifier(db, quoted=quoted),
5494        catalog=to_identifier(catalog, quoted=quoted),
5495    )
5496
5497
5498def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5499    """Cast an expression to a data type.
5500
5501    Example:
5502        >>> cast('x + 1', 'int').sql()
5503        'CAST(x + 1 AS INT)'
5504
5505    Args:
5506        expression: The expression to cast.
5507        to: The datatype to cast to.
5508
5509    Returns:
5510        The new Cast instance.
5511    """
5512    expression = maybe_parse(expression, **opts)
5513    return Cast(this=expression, to=DataType.build(to, **opts))
5514
5515
5516def table_(
5517    table: Identifier | str,
5518    db: t.Optional[Identifier | str] = None,
5519    catalog: t.Optional[Identifier | str] = None,
5520    quoted: t.Optional[bool] = None,
5521    alias: t.Optional[Identifier | str] = None,
5522) -> Table:
5523    """Build a Table.
5524
5525    Args:
5526        table: Table name.
5527        db: Database name.
5528        catalog: Catalog name.
5529        quote: Whether to force quotes on the table's identifiers.
5530        alias: Table's alias.
5531
5532    Returns:
5533        The new Table instance.
5534    """
5535    return Table(
5536        this=to_identifier(table, quoted=quoted),
5537        db=to_identifier(db, quoted=quoted),
5538        catalog=to_identifier(catalog, quoted=quoted),
5539        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5540    )
5541
5542
5543def values(
5544    values: t.Iterable[t.Tuple[t.Any, ...]],
5545    alias: t.Optional[str] = None,
5546    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5547) -> Values:
5548    """Build VALUES statement.
5549
5550    Example:
5551        >>> values([(1, '2')]).sql()
5552        "VALUES (1, '2')"
5553
5554    Args:
5555        values: values statements that will be converted to SQL
5556        alias: optional alias
5557        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5558         If either are provided then an alias is also required.
5559
5560    Returns:
5561        Values: the Values expression object
5562    """
5563    if columns and not alias:
5564        raise ValueError("Alias is required when providing columns")
5565
5566    return Values(
5567        expressions=[convert(tup) for tup in values],
5568        alias=(
5569            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5570            if columns
5571            else (TableAlias(this=to_identifier(alias)) if alias else None)
5572        ),
5573    )
5574
5575
5576def var(name: t.Optional[ExpOrStr]) -> Var:
5577    """Build a SQL variable.
5578
5579    Example:
5580        >>> repr(var('x'))
5581        '(VAR this: x)'
5582
5583        >>> repr(var(column('x', table='y')))
5584        '(VAR this: x)'
5585
5586    Args:
5587        name: The name of the var or an expression who's name will become the var.
5588
5589    Returns:
5590        The new variable node.
5591    """
5592    if not name:
5593        raise ValueError("Cannot convert empty name into var.")
5594
5595    if isinstance(name, Expression):
5596        name = name.name
5597    return Var(this=name)
5598
5599
5600def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5601    """Build ALTER TABLE... RENAME... expression
5602
5603    Args:
5604        old_name: The old name of the table
5605        new_name: The new name of the table
5606
5607    Returns:
5608        Alter table expression
5609    """
5610    old_table = to_table(old_name)
5611    new_table = to_table(new_name)
5612    return AlterTable(
5613        this=old_table,
5614        actions=[
5615            RenameTable(this=new_table),
5616        ],
5617    )
5618
5619
5620def convert(value: t.Any, copy: bool = False) -> Expression:
5621    """Convert a python value into an expression object.
5622
5623    Raises an error if a conversion is not possible.
5624
5625    Args:
5626        value: A python object.
5627        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5628
5629    Returns:
5630        Expression: the equivalent expression object.
5631    """
5632    if isinstance(value, Expression):
5633        return _maybe_copy(value, copy)
5634    if isinstance(value, str):
5635        return Literal.string(value)
5636    if isinstance(value, bool):
5637        return Boolean(this=value)
5638    if value is None or (isinstance(value, float) and math.isnan(value)):
5639        return NULL
5640    if isinstance(value, numbers.Number):
5641        return Literal.number(value)
5642    if isinstance(value, datetime.datetime):
5643        datetime_literal = Literal.string(
5644            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5645        )
5646        return TimeStrToTime(this=datetime_literal)
5647    if isinstance(value, datetime.date):
5648        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5649        return DateStrToDate(this=date_literal)
5650    if isinstance(value, tuple):
5651        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5652    if isinstance(value, list):
5653        return Array(expressions=[convert(v, copy=copy) for v in value])
5654    if isinstance(value, dict):
5655        return Map(
5656            keys=[convert(k, copy=copy) for k in value],
5657            values=[convert(v, copy=copy) for v in value.values()],
5658        )
5659    raise ValueError(f"Cannot convert {value}")
5660
5661
5662def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5663    """
5664    Replace children of an expression with the result of a lambda fun(child) -> exp.
5665    """
5666    for k, v in expression.args.items():
5667        is_list_arg = type(v) is list
5668
5669        child_nodes = v if is_list_arg else [v]
5670        new_child_nodes = []
5671
5672        for cn in child_nodes:
5673            if isinstance(cn, Expression):
5674                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5675                    new_child_nodes.append(child_node)
5676                    child_node.parent = expression
5677                    child_node.arg_key = k
5678            else:
5679                new_child_nodes.append(cn)
5680
5681        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)
5682
5683
5684def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5685    """
5686    Return all table names referenced through columns in an expression.
5687
5688    Example:
5689        >>> import sqlglot
5690        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5691        ['a', 'c']
5692
5693    Args:
5694        expression: expression to find table names.
5695        exclude: a table name to exclude
5696
5697    Returns:
5698        A list of unique names.
5699    """
5700    return {
5701        table
5702        for table in (column.table for column in expression.find_all(Column))
5703        if table and table != exclude
5704    }
5705
5706
5707def table_name(table: Table | str) -> str:
5708    """Get the full name of a table as a string.
5709
5710    Args:
5711        table: table expression node or string.
5712
5713    Examples:
5714        >>> from sqlglot import exp, parse_one
5715        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5716        'a.b.c'
5717
5718    Returns:
5719        The table name.
5720    """
5721
5722    table = maybe_parse(table, into=Table)
5723
5724    if not table:
5725        raise ValueError(f"Cannot parse {table}")
5726
5727    return ".".join(part for part in (table.text("catalog"), table.text("db"), table.name) if part)
5728
5729
5730def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5731    """Replace all tables in expression according to the mapping.
5732
5733    Args:
5734        expression: expression node to be transformed and replaced.
5735        mapping: mapping of table names.
5736        copy: whether or not to copy the expression.
5737
5738    Examples:
5739        >>> from sqlglot import exp, parse_one
5740        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5741        'SELECT * FROM c'
5742
5743    Returns:
5744        The mapped expression.
5745    """
5746
5747    def _replace_tables(node: Expression) -> Expression:
5748        if isinstance(node, Table):
5749            new_name = mapping.get(table_name(node))
5750            if new_name:
5751                return to_table(
5752                    new_name,
5753                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5754                )
5755        return node
5756
5757    return expression.transform(_replace_tables, copy=copy)
5758
5759
5760def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5761    """Replace placeholders in an expression.
5762
5763    Args:
5764        expression: expression node to be transformed and replaced.
5765        args: positional names that will substitute unnamed placeholders in the given order.
5766        kwargs: keyword arguments that will substitute named placeholders.
5767
5768    Examples:
5769        >>> from sqlglot import exp, parse_one
5770        >>> replace_placeholders(
5771        ...     parse_one("select * from :tbl where ? = ?"),
5772        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5773        ... ).sql()
5774        "SELECT * FROM foo WHERE str_col = 'b'"
5775
5776    Returns:
5777        The mapped expression.
5778    """
5779
5780    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5781        if isinstance(node, Placeholder):
5782            if node.name:
5783                new_name = kwargs.get(node.name)
5784                if new_name:
5785                    return convert(new_name)
5786            else:
5787                try:
5788                    return convert(next(args))
5789                except StopIteration:
5790                    pass
5791        return node
5792
5793    return expression.transform(_replace_placeholders, iter(args), **kwargs)
5794
5795
5796def expand(
5797    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5798) -> Expression:
5799    """Transforms an expression by expanding all referenced sources into subqueries.
5800
5801    Examples:
5802        >>> from sqlglot import parse_one
5803        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5804        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5805
5806        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5807        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5808
5809    Args:
5810        expression: The expression to expand.
5811        sources: A dictionary of name to Subqueryables.
5812        copy: Whether or not to copy the expression during transformation. Defaults to True.
5813
5814    Returns:
5815        The transformed expression.
5816    """
5817
5818    def _expand(node: Expression):
5819        if isinstance(node, Table):
5820            name = table_name(node)
5821            source = sources.get(name)
5822            if source:
5823                subquery = source.subquery(node.alias or name)
5824                subquery.comments = [f"source: {name}"]
5825                return subquery.transform(_expand, copy=False)
5826        return node
5827
5828    return expression.transform(_expand, copy=copy)
5829
5830
5831def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5832    """
5833    Returns a Func expression.
5834
5835    Examples:
5836        >>> func("abs", 5).sql()
5837        'ABS(5)'
5838
5839        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5840        'CAST(5 AS DOUBLE)'
5841
5842    Args:
5843        name: the name of the function to build.
5844        args: the args used to instantiate the function of interest.
5845        dialect: the source dialect.
5846        kwargs: the kwargs used to instantiate the function of interest.
5847
5848    Note:
5849        The arguments `args` and `kwargs` are mutually exclusive.
5850
5851    Returns:
5852        An instance of the function of interest, or an anonymous function, if `name` doesn't
5853        correspond to an existing `sqlglot.expressions.Func` class.
5854    """
5855    if args and kwargs:
5856        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5857
5858    from sqlglot.dialects.dialect import Dialect
5859
5860    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5861    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5862
5863    parser = Dialect.get_or_raise(dialect)().parser()
5864    from_args_list = parser.FUNCTIONS.get(name.upper())
5865
5866    if from_args_list:
5867        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5868    else:
5869        kwargs = kwargs or {"expressions": converted}
5870        function = Anonymous(this=name, **kwargs)
5871
5872    for error_message in function.error_messages(converted):
5873        raise ValueError(error_message)
5874
5875    return function
5876
5877
5878def true() -> Boolean:
5879    """
5880    Returns a true Boolean expression.
5881    """
5882    return Boolean(this=True)
5883
5884
5885def false() -> Boolean:
5886    """
5887    Returns a false Boolean expression.
5888    """
5889    return Boolean(this=False)
5890
5891
5892def null() -> Null:
5893    """
5894    Returns a Null expression.
5895    """
5896    return Null()
5897
5898
5899# TODO: deprecate this
5900TRUE = Boolean(this=True)
5901FALSE = Boolean(this=False)
5902NULL = Null()
class Expression:
 55class Expression(metaclass=_Expression):
 56    """
 57    The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary
 58    context, such as its child expressions, their names (arg keys), and whether a given child expression
 59    is optional or not.
 60
 61    Attributes:
 62        key: a unique key for each class in the Expression hierarchy. This is useful for hashing
 63            and representing expressions as strings.
 64        arg_types: determines what arguments (child nodes) are supported by an expression. It
 65            maps arg keys to booleans that indicate whether the corresponding args are optional.
 66        parent: a reference to the parent expression (or None, in case of root expressions).
 67        arg_key: the arg key an expression is associated with, i.e. the name its parent expression
 68            uses to refer to it.
 69        comments: a list of comments that are associated with a given expression. This is used in
 70            order to preserve comments when transpiling SQL code.
 71        _type: the `sqlglot.expressions.DataType` type of an expression. This is inferred by the
 72            optimizer, in order to enable some transformations that require type information.
 73
 74    Example:
 75        >>> class Foo(Expression):
 76        ...     arg_types = {"this": True, "expression": False}
 77
 78        The above definition informs us that Foo is an Expression that requires an argument called
 79        "this" and may also optionally receive an argument called "expression".
 80
 81    Args:
 82        args: a mapping used for retrieving the arguments of an expression, given their arg keys.
 83    """
 84
 85    key = "expression"
 86    arg_types = {"this": True}
 87    __slots__ = ("args", "parent", "arg_key", "comments", "_type", "_meta", "_hash")
 88
 89    def __init__(self, **args: t.Any):
 90        self.args: t.Dict[str, t.Any] = args
 91        self.parent: t.Optional[Expression] = None
 92        self.arg_key: t.Optional[str] = None
 93        self.comments: t.Optional[t.List[str]] = None
 94        self._type: t.Optional[DataType] = None
 95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
 96        self._hash: t.Optional[int] = None
 97
 98        for arg_key, value in self.args.items():
 99            self._set_parent(arg_key, value)
100
101    def __eq__(self, other) -> bool:
102        return type(self) is type(other) and hash(self) == hash(other)
103
104    @property
105    def hashable_args(self) -> t.Any:
106        args = (self.args.get(k) for k in self.arg_types)
107
108        return tuple(
109            (tuple(_norm_arg(a) for a in arg) if arg else None)
110            if type(arg) is list
111            else (_norm_arg(arg) if arg is not None and arg is not False else None)
112            for arg in args
113        )
114
115    def __hash__(self) -> int:
116        if self._hash is not None:
117            return self._hash
118
119        return hash((self.__class__, self.hashable_args))
120
121    @property
122    def this(self):
123        """
124        Retrieves the argument with key "this".
125        """
126        return self.args.get("this")
127
128    @property
129    def expression(self):
130        """
131        Retrieves the argument with key "expression".
132        """
133        return self.args.get("expression")
134
135    @property
136    def expressions(self):
137        """
138        Retrieves the argument with key "expressions".
139        """
140        return self.args.get("expressions") or []
141
142    def text(self, key) -> str:
143        """
144        Returns a textual representation of the argument corresponding to "key". This can only be used
145        for args that are strings or leaf Expression instances, such as identifiers and literals.
146        """
147        field = self.args.get(key)
148        if isinstance(field, str):
149            return field
150        if isinstance(field, (Identifier, Literal, Var)):
151            return field.this
152        if isinstance(field, (Star, Null)):
153            return field.name
154        return ""
155
156    @property
157    def is_string(self) -> bool:
158        """
159        Checks whether a Literal expression is a string.
160        """
161        return isinstance(self, Literal) and self.args["is_string"]
162
163    @property
164    def is_number(self) -> bool:
165        """
166        Checks whether a Literal expression is a number.
167        """
168        return isinstance(self, Literal) and not self.args["is_string"]
169
170    @property
171    def is_int(self) -> bool:
172        """
173        Checks whether a Literal expression is an integer.
174        """
175        if self.is_number:
176            try:
177                int(self.name)
178                return True
179            except ValueError:
180                pass
181        return False
182
183    @property
184    def is_star(self) -> bool:
185        """Checks whether an expression is a star."""
186        return isinstance(self, Star) or (isinstance(self, Column) and isinstance(self.this, Star))
187
188    @property
189    def alias(self) -> str:
190        """
191        Returns the alias of the expression, or an empty string if it's not aliased.
192        """
193        if isinstance(self.args.get("alias"), TableAlias):
194            return self.args["alias"].name
195        return self.text("alias")
196
197    @property
198    def name(self) -> str:
199        return self.text("this")
200
201    @property
202    def alias_or_name(self) -> str:
203        return self.alias or self.name
204
205    @property
206    def output_name(self) -> str:
207        """
208        Name of the output column if this expression is a selection.
209
210        If the Expression has no output name, an empty string is returned.
211
212        Example:
213            >>> from sqlglot import parse_one
214            >>> parse_one("SELECT a").expressions[0].output_name
215            'a'
216            >>> parse_one("SELECT b AS c").expressions[0].output_name
217            'c'
218            >>> parse_one("SELECT 1 + 2").expressions[0].output_name
219            ''
220        """
221        return ""
222
223    @property
224    def type(self) -> t.Optional[DataType]:
225        return self._type
226
227    @type.setter
228    def type(self, dtype: t.Optional[DataType | DataType.Type | str]) -> None:
229        if dtype and not isinstance(dtype, DataType):
230            dtype = DataType.build(dtype)
231        self._type = dtype  # type: ignore
232
233    @property
234    def meta(self) -> t.Dict[str, t.Any]:
235        if self._meta is None:
236            self._meta = {}
237        return self._meta
238
239    def __deepcopy__(self, memo):
240        copy = self.__class__(**deepcopy(self.args))
241        if self.comments is not None:
242            copy.comments = deepcopy(self.comments)
243
244        if self._type is not None:
245            copy._type = self._type.copy()
246
247        if self._meta is not None:
248            copy._meta = deepcopy(self._meta)
249
250        return copy
251
252    def copy(self):
253        """
254        Returns a deep copy of the expression.
255        """
256        new = deepcopy(self)
257        new.parent = self.parent
258        return new
259
260    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
261        if self.comments is None:
262            self.comments = []
263        if comments:
264            self.comments.extend(comments)
265
266    def append(self, arg_key: str, value: t.Any) -> None:
267        """
268        Appends value to arg_key if it's a list or sets it as a new list.
269
270        Args:
271            arg_key (str): name of the list expression arg
272            value (Any): value to append to the list
273        """
274        if not isinstance(self.args.get(arg_key), list):
275            self.args[arg_key] = []
276        self.args[arg_key].append(value)
277        self._set_parent(arg_key, value)
278
279    def set(self, arg_key: str, value: t.Any) -> None:
280        """
281        Sets `arg_key` to `value`.
282
283        Args:
284            arg_key (str): name of the expression arg.
285            value: value to set the arg to.
286        """
287        self.args[arg_key] = value
288        self._set_parent(arg_key, value)
289
290    def _set_parent(self, arg_key: str, value: t.Any) -> None:
291        if hasattr(value, "parent"):
292            value.parent = self
293            value.arg_key = arg_key
294        elif type(value) is list:
295            for v in value:
296                if hasattr(v, "parent"):
297                    v.parent = self
298                    v.arg_key = arg_key
299
300    @property
301    def depth(self) -> int:
302        """
303        Returns the depth of this tree.
304        """
305        if self.parent:
306            return self.parent.depth + 1
307        return 0
308
309    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
310        """Yields the key and expression for all arguments, exploding list args."""
311        for k, vs in self.args.items():
312            if type(vs) is list:
313                for v in vs:
314                    if hasattr(v, "parent"):
315                        yield k, v
316            else:
317                if hasattr(vs, "parent"):
318                    yield k, vs
319
320    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
321        """
322        Returns the first node in this tree which matches at least one of
323        the specified types.
324
325        Args:
326            expression_types: the expression type(s) to match.
327            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
328
329        Returns:
330            The node which matches the criteria or None if no such node was found.
331        """
332        return next(self.find_all(*expression_types, bfs=bfs), None)
333
334    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
335        """
336        Returns a generator object which visits all nodes in this tree and only
337        yields those that match at least one of the specified expression types.
338
339        Args:
340            expression_types: the expression type(s) to match.
341            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression
349
350    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)
364
365    @property
366    def parent_select(self) -> t.Optional[Select]:
367        """
368        Returns the parent select statement.
369        """
370        return self.find_ancestor(Select)
371
372    @property
373    def same_parent(self) -> bool:
374        """Returns if the parent is the same class as itself."""
375        return type(self.parent) is self.__class__
376
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression
385
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)
403
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)
419
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))
439
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression
448
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self
456
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())
462
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node
472
473    def __str__(self) -> str:
474        return self.sql()
475
476    def __repr__(self) -> str:
477        return self._to_s()
478
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)
493
494    def _to_s(self, hide_missing: bool = True, level: int = 0) -> str:
495        indent = "" if not level else "\n"
496        indent += "".join(["  "] * level)
497        left = f"({self.key.upper()} "
498
499        args: t.Dict[str, t.Any] = {
500            k: ", ".join(
501                v._to_s(hide_missing=hide_missing, level=level + 1)
502                if hasattr(v, "_to_s")
503                else str(v)
504                for v in ensure_list(vs)
505                if v is not None
506            )
507            for k, vs in self.args.items()
508        }
509        args["comments"] = self.comments
510        args["type"] = self.type
511        args = {k: v for k, v in args.items() if v or not hide_missing}
512
513        right = ", ".join(f"{k}: {v}" for k, v in args.items())
514        right += ")"
515
516        return indent + left + right
517
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node
544
545    @t.overload
546    def replace(self, expression: E) -> E:
547        ...
548
549    @t.overload
550    def replace(self, expression: None) -> None:
551        ...
552
553    def replace(self, expression):
554        """
555        Swap out this expression with a new expression.
556
557        For example::
558
559            >>> tree = Select().select("x").from_("tbl")
560            >>> tree.find(Column).replace(Column(this="y"))
561            (COLUMN this: y)
562            >>> tree.sql()
563            'SELECT y FROM tbl'
564
565        Args:
566            expression: new node
567
568        Returns:
569            The new expression or expressions.
570        """
571        if not self.parent:
572            return expression
573
574        parent = self.parent
575        self.parent = None
576
577        replace_children(parent, lambda child: expression if child is self else child)
578        return expression
579
580    def pop(self: E) -> E:
581        """
582        Remove this expression from its AST.
583
584        Returns:
585            The popped expression.
586        """
587        self.replace(None)
588        return self
589
590    def assert_is(self, type_: t.Type[E]) -> E:
591        """
592        Assert that this `Expression` is an instance of `type_`.
593
594        If it is NOT an instance of `type_`, this raises an assertion error.
595        Otherwise, this returns this expression.
596
597        Examples:
598            This is useful for type security in chained expressions:
599
600            >>> import sqlglot
601            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
602            'SELECT x, z FROM y'
603        """
604        assert isinstance(self, type_)
605        return self
606
607    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
608        """
609        Checks if this expression is valid (e.g. all mandatory args are set).
610
611        Args:
612            args: a sequence of values that were used to instantiate a Func expression. This is used
613                to check that the provided arguments don't exceed the function argument limit.
614
615        Returns:
616            A list of error messages for all possible errors that were found.
617        """
618        errors: t.List[str] = []
619
620        for k in self.args:
621            if k not in self.arg_types:
622                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
623        for k, mandatory in self.arg_types.items():
624            v = self.args.get(k)
625            if mandatory and (v is None or (isinstance(v, list) and not v)):
626                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
627
628        if (
629            args
630            and isinstance(self, Func)
631            and len(args) > len(self.arg_types)
632            and not self.is_var_len_args
633        ):
634            errors.append(
635                f"The number of provided arguments ({len(args)}) is greater than "
636                f"the maximum number of supported arguments ({len(self.arg_types)})"
637            )
638
639        return errors
640
641    def dump(self):
642        """
643        Dump this Expression to a JSON-serializable dict.
644        """
645        from sqlglot.serde import dump
646
647        return dump(self)
648
649    @classmethod
650    def load(cls, obj):
651        """
652        Load a dict (as returned by `Expression.dump`) into an Expression instance.
653        """
654        from sqlglot.serde import load
655
656        return load(obj)

The base class for all expressions in a syntax tree. Each Expression encapsulates any necessary context, such as its child expressions, their names (arg keys), and whether a given child expression is optional or not.

Attributes:
  • key: a unique key for each class in the Expression hierarchy. This is useful for hashing and representing expressions as strings.
  • arg_types: determines what arguments (child nodes) are supported by an expression. It maps arg keys to booleans that indicate whether the corresponding args are optional.
  • parent: a reference to the parent expression (or None, in case of root expressions).
  • arg_key: the arg key an expression is associated with, i.e. the name its parent expression uses to refer to it.
  • comments: a list of comments that are associated with a given expression. This is used in order to preserve comments when transpiling SQL code.
  • _type: the sqlglot.expressions.DataType type of an expression. This is inferred by the optimizer, in order to enable some transformations that require type information.
Example:
>>> class Foo(Expression):
...     arg_types = {"this": True, "expression": False}

The above definition informs us that Foo is an Expression that requires an argument called "this" and may also optionally receive an argument called "expression".

Arguments:
  • args: a mapping used for retrieving the arguments of an expression, given their arg keys.
Expression(**args: Any)
89    def __init__(self, **args: t.Any):
90        self.args: t.Dict[str, t.Any] = args
91        self.parent: t.Optional[Expression] = None
92        self.arg_key: t.Optional[str] = None
93        self.comments: t.Optional[t.List[str]] = None
94        self._type: t.Optional[DataType] = None
95        self._meta: t.Optional[t.Dict[str, t.Any]] = None
96        self._hash: t.Optional[int] = None
97
98        for arg_key, value in self.args.items():
99            self._set_parent(arg_key, value)
key = 'expression'
arg_types = {'this': True}
args: Dict[str, Any]
parent: Optional[sqlglot.expressions.Expression]
arg_key: Optional[str]
comments: Optional[List[str]]
hashable_args: Any
this

Retrieves the argument with key "this".

expression

Retrieves the argument with key "expression".

expressions

Retrieves the argument with key "expressions".

def text(self, key) -> str:
142    def text(self, key) -> str:
143        """
144        Returns a textual representation of the argument corresponding to "key". This can only be used
145        for args that are strings or leaf Expression instances, such as identifiers and literals.
146        """
147        field = self.args.get(key)
148        if isinstance(field, str):
149            return field
150        if isinstance(field, (Identifier, Literal, Var)):
151            return field.this
152        if isinstance(field, (Star, Null)):
153            return field.name
154        return ""

Returns a textual representation of the argument corresponding to "key". This can only be used for args that are strings or leaf Expression instances, such as identifiers and literals.

is_string: bool

Checks whether a Literal expression is a string.

is_number: bool

Checks whether a Literal expression is a number.

is_int: bool

Checks whether a Literal expression is an integer.

is_star: bool

Checks whether an expression is a star.

alias: str

Returns the alias of the expression, or an empty string if it's not aliased.

name: str
alias_or_name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
meta: Dict[str, Any]
def copy(self):
252    def copy(self):
253        """
254        Returns a deep copy of the expression.
255        """
256        new = deepcopy(self)
257        new.parent = self.parent
258        return new

Returns a deep copy of the expression.

def add_comments(self, comments: Optional[List[str]]) -> None:
260    def add_comments(self, comments: t.Optional[t.List[str]]) -> None:
261        if self.comments is None:
262            self.comments = []
263        if comments:
264            self.comments.extend(comments)
def append(self, arg_key: str, value: Any) -> None:
266    def append(self, arg_key: str, value: t.Any) -> None:
267        """
268        Appends value to arg_key if it's a list or sets it as a new list.
269
270        Args:
271            arg_key (str): name of the list expression arg
272            value (Any): value to append to the list
273        """
274        if not isinstance(self.args.get(arg_key), list):
275            self.args[arg_key] = []
276        self.args[arg_key].append(value)
277        self._set_parent(arg_key, value)

Appends value to arg_key if it's a list or sets it as a new list.

Arguments:
  • arg_key (str): name of the list expression arg
  • value (Any): value to append to the list
def set(self, arg_key: str, value: Any) -> None:
279    def set(self, arg_key: str, value: t.Any) -> None:
280        """
281        Sets `arg_key` to `value`.
282
283        Args:
284            arg_key (str): name of the expression arg.
285            value: value to set the arg to.
286        """
287        self.args[arg_key] = value
288        self._set_parent(arg_key, value)

Sets arg_key to value.

Arguments:
  • arg_key (str): name of the expression arg.
  • value: value to set the arg to.
depth: int

Returns the depth of this tree.

def iter_expressions(self) -> Iterator[Tuple[str, sqlglot.expressions.Expression]]:
309    def iter_expressions(self) -> t.Iterator[t.Tuple[str, Expression]]:
310        """Yields the key and expression for all arguments, exploding list args."""
311        for k, vs in self.args.items():
312            if type(vs) is list:
313                for v in vs:
314                    if hasattr(v, "parent"):
315                        yield k, v
316            else:
317                if hasattr(vs, "parent"):
318                    yield k, vs

Yields the key and expression for all arguments, exploding list args.

def find(self, *expression_types: Type[~E], bfs: bool = True) -> Optional[~E]:
320    def find(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Optional[E]:
321        """
322        Returns the first node in this tree which matches at least one of
323        the specified types.
324
325        Args:
326            expression_types: the expression type(s) to match.
327            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
328
329        Returns:
330            The node which matches the criteria or None if no such node was found.
331        """
332        return next(self.find_all(*expression_types, bfs=bfs), None)

Returns the first node in this tree which matches at least one of the specified types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The node which matches the criteria or None if no such node was found.

def find_all(self, *expression_types: Type[~E], bfs: bool = True) -> Iterator[~E]:
334    def find_all(self, *expression_types: t.Type[E], bfs: bool = True) -> t.Iterator[E]:
335        """
336        Returns a generator object which visits all nodes in this tree and only
337        yields those that match at least one of the specified expression types.
338
339        Args:
340            expression_types: the expression type(s) to match.
341            bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
342
343        Returns:
344            The generator object.
345        """
346        for expression, *_ in self.walk(bfs=bfs):
347            if isinstance(expression, expression_types):
348                yield expression

Returns a generator object which visits all nodes in this tree and only yields those that match at least one of the specified expression types.

Arguments:
  • expression_types: the expression type(s) to match.
  • bfs: whether to search the AST using the BFS algorithm (DFS is used if false).
Returns:

The generator object.

def find_ancestor(self, *expression_types: Type[~E]) -> Optional[~E]:
350    def find_ancestor(self, *expression_types: t.Type[E]) -> t.Optional[E]:
351        """
352        Returns a nearest parent matching expression_types.
353
354        Args:
355            expression_types: the expression type(s) to match.
356
357        Returns:
358            The parent node.
359        """
360        ancestor = self.parent
361        while ancestor and not isinstance(ancestor, expression_types):
362            ancestor = ancestor.parent
363        return t.cast(E, ancestor)

Returns a nearest parent matching expression_types.

Arguments:
  • expression_types: the expression type(s) to match.
Returns:

The parent node.

parent_select: Optional[sqlglot.expressions.Select]

Returns the parent select statement.

same_parent: bool

Returns if the parent is the same class as itself.

def root(self) -> sqlglot.expressions.Expression:
377    def root(self) -> Expression:
378        """
379        Returns the root expression of this tree.
380        """
381        expression = self
382        while expression.parent:
383            expression = expression.parent
384        return expression

Returns the root expression of this tree.

def walk(self, bfs=True, prune=None):
386    def walk(self, bfs=True, prune=None):
387        """
388        Returns a generator object which visits all nodes in this tree.
389
390        Args:
391            bfs (bool): if set to True the BFS traversal order will be applied,
392                otherwise the DFS traversal will be used instead.
393            prune ((node, parent, arg_key) -> bool): callable that returns True if
394                the generator should stop traversing this branch of the tree.
395
396        Returns:
397            the generator object.
398        """
399        if bfs:
400            yield from self.bfs(prune=prune)
401        else:
402            yield from self.dfs(prune=prune)

Returns a generator object which visits all nodes in this tree.

Arguments:
  • bfs (bool): if set to True the BFS traversal order will be applied, otherwise the DFS traversal will be used instead.
  • prune ((node, parent, arg_key) -> bool): callable that returns True if the generator should stop traversing this branch of the tree.
Returns:

the generator object.

def dfs(self, parent=None, key=None, prune=None):
404    def dfs(self, parent=None, key=None, prune=None):
405        """
406        Returns a generator object which visits all nodes in this tree in
407        the DFS (Depth-first) order.
408
409        Returns:
410            The generator object.
411        """
412        parent = parent or self.parent
413        yield self, parent, key
414        if prune and prune(self, parent, key):
415            return
416
417        for k, v in self.iter_expressions():
418            yield from v.dfs(self, k, prune)

Returns a generator object which visits all nodes in this tree in the DFS (Depth-first) order.

Returns:

The generator object.

def bfs(self, prune=None):
420    def bfs(self, prune=None):
421        """
422        Returns a generator object which visits all nodes in this tree in
423        the BFS (Breadth-first) order.
424
425        Returns:
426            The generator object.
427        """
428        queue = deque([(self, self.parent, None)])
429
430        while queue:
431            item, parent, key = queue.popleft()
432
433            yield item, parent, key
434            if prune and prune(item, parent, key):
435                continue
436
437            for k, v in item.iter_expressions():
438                queue.append((v, item, k))

Returns a generator object which visits all nodes in this tree in the BFS (Breadth-first) order.

Returns:

The generator object.

def unnest(self):
440    def unnest(self):
441        """
442        Returns the first non parenthesis child or self.
443        """
444        expression = self
445        while type(expression) is Paren:
446            expression = expression.this
447        return expression

Returns the first non parenthesis child or self.

def unalias(self):
449    def unalias(self):
450        """
451        Returns the inner expression if this is an Alias.
452        """
453        if isinstance(self, Alias):
454            return self.this
455        return self

Returns the inner expression if this is an Alias.

def unnest_operands(self):
457    def unnest_operands(self):
458        """
459        Returns unnested operands as a tuple.
460        """
461        return tuple(arg.unnest() for _, arg in self.iter_expressions())

Returns unnested operands as a tuple.

def flatten(self, unnest=True):
463    def flatten(self, unnest=True):
464        """
465        Returns a generator which yields child nodes who's parents are the same class.
466
467        A AND B AND C -> [A, B, C]
468        """
469        for node, _, _ in self.dfs(prune=lambda n, p, *_: p and not type(n) is self.__class__):
470            if not type(node) is self.__class__:
471                yield node.unnest() if unnest else node

Returns a generator which yields child nodes who's parents are the same class.

A AND B AND C -> [A, B, C]

def sql( self, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> str:
479    def sql(self, dialect: DialectType = None, **opts) -> str:
480        """
481        Returns SQL string representation of this tree.
482
483        Args:
484            dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
485            opts: other `sqlglot.generator.Generator` options.
486
487        Returns:
488            The SQL string.
489        """
490        from sqlglot.dialects import Dialect
491
492        return Dialect.get_or_raise(dialect)().generate(self, **opts)

Returns SQL string representation of this tree.

Arguments:
  • dialect: the dialect of the output SQL string (eg. "spark", "hive", "presto", "mysql").
  • opts: other sqlglot.generator.Generator options.
Returns:

The SQL string.

def transform(self, fun, *args, copy=True, **kwargs):
518    def transform(self, fun, *args, copy=True, **kwargs):
519        """
520        Recursively visits all tree nodes (excluding already transformed ones)
521        and applies the given transformation function to each node.
522
523        Args:
524            fun (function): a function which takes a node as an argument and returns a
525                new transformed node or the same node without modifications. If the function
526                returns None, then the corresponding node will be removed from the syntax tree.
527            copy (bool): if set to True a new tree instance is constructed, otherwise the tree is
528                modified in place.
529
530        Returns:
531            The transformed tree.
532        """
533        node = self.copy() if copy else self
534        new_node = fun(node, *args, **kwargs)
535
536        if new_node is None or not isinstance(new_node, Expression):
537            return new_node
538        if new_node is not node:
539            new_node.parent = node.parent
540            return new_node
541
542        replace_children(new_node, lambda child: child.transform(fun, *args, copy=False, **kwargs))
543        return new_node

Recursively visits all tree nodes (excluding already transformed ones) and applies the given transformation function to each node.

Arguments:
  • fun (function): a function which takes a node as an argument and returns a new transformed node or the same node without modifications. If the function returns None, then the corresponding node will be removed from the syntax tree.
  • copy (bool): if set to True a new tree instance is constructed, otherwise the tree is modified in place.
Returns:

The transformed tree.

def replace(self, expression):
553    def replace(self, expression):
554        """
555        Swap out this expression with a new expression.
556
557        For example::
558
559            >>> tree = Select().select("x").from_("tbl")
560            >>> tree.find(Column).replace(Column(this="y"))
561            (COLUMN this: y)
562            >>> tree.sql()
563            'SELECT y FROM tbl'
564
565        Args:
566            expression: new node
567
568        Returns:
569            The new expression or expressions.
570        """
571        if not self.parent:
572            return expression
573
574        parent = self.parent
575        self.parent = None
576
577        replace_children(parent, lambda child: expression if child is self else child)
578        return expression

Swap out this expression with a new expression.

For example::

>>> tree = Select().select("x").from_("tbl")
>>> tree.find(Column).replace(Column(this="y"))
(COLUMN this: y)
>>> tree.sql()
'SELECT y FROM tbl'
Arguments:
  • expression: new node
Returns:

The new expression or expressions.

def pop(self: ~E) -> ~E:
580    def pop(self: E) -> E:
581        """
582        Remove this expression from its AST.
583
584        Returns:
585            The popped expression.
586        """
587        self.replace(None)
588        return self

Remove this expression from its AST.

Returns:

The popped expression.

def assert_is(self, type_: Type[~E]) -> ~E:
590    def assert_is(self, type_: t.Type[E]) -> E:
591        """
592        Assert that this `Expression` is an instance of `type_`.
593
594        If it is NOT an instance of `type_`, this raises an assertion error.
595        Otherwise, this returns this expression.
596
597        Examples:
598            This is useful for type security in chained expressions:
599
600            >>> import sqlglot
601            >>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
602            'SELECT x, z FROM y'
603        """
604        assert isinstance(self, type_)
605        return self

Assert that this Expression is an instance of type_.

If it is NOT an instance of type_, this raises an assertion error. Otherwise, this returns this expression.

Examples:

This is useful for type security in chained expressions:

>>> import sqlglot
>>> sqlglot.parse_one("SELECT x from y").assert_is(Select).select("z").sql()
'SELECT x, z FROM y'
def error_messages(self, args: Optional[Sequence] = None) -> List[str]:
607    def error_messages(self, args: t.Optional[t.Sequence] = None) -> t.List[str]:
608        """
609        Checks if this expression is valid (e.g. all mandatory args are set).
610
611        Args:
612            args: a sequence of values that were used to instantiate a Func expression. This is used
613                to check that the provided arguments don't exceed the function argument limit.
614
615        Returns:
616            A list of error messages for all possible errors that were found.
617        """
618        errors: t.List[str] = []
619
620        for k in self.args:
621            if k not in self.arg_types:
622                errors.append(f"Unexpected keyword: '{k}' for {self.__class__}")
623        for k, mandatory in self.arg_types.items():
624            v = self.args.get(k)
625            if mandatory and (v is None or (isinstance(v, list) and not v)):
626                errors.append(f"Required keyword: '{k}' missing for {self.__class__}")
627
628        if (
629            args
630            and isinstance(self, Func)
631            and len(args) > len(self.arg_types)
632            and not self.is_var_len_args
633        ):
634            errors.append(
635                f"The number of provided arguments ({len(args)}) is greater than "
636                f"the maximum number of supported arguments ({len(self.arg_types)})"
637            )
638
639        return errors

Checks if this expression is valid (e.g. all mandatory args are set).

Arguments:
  • args: a sequence of values that were used to instantiate a Func expression. This is used to check that the provided arguments don't exceed the function argument limit.
Returns:

A list of error messages for all possible errors that were found.

def dump(self):
641    def dump(self):
642        """
643        Dump this Expression to a JSON-serializable dict.
644        """
645        from sqlglot.serde import dump
646
647        return dump(self)

Dump this Expression to a JSON-serializable dict.

@classmethod
def load(cls, obj):
649    @classmethod
650    def load(cls, obj):
651        """
652        Load a dict (as returned by `Expression.dump`) into an Expression instance.
653        """
654        from sqlglot.serde import load
655
656        return load(obj)

Load a dict (as returned by Expression.dump) into an Expression instance.

IntoType = typing.Union[str, typing.Type[sqlglot.expressions.Expression], typing.Collection[typing.Union[str, typing.Type[sqlglot.expressions.Expression]]]]
ExpOrStr = typing.Union[str, sqlglot.expressions.Expression]
class Condition(Expression):
667class Condition(Expression):
668    def and_(
669        self,
670        *expressions: t.Optional[ExpOrStr],
671        dialect: DialectType = None,
672        copy: bool = True,
673        **opts,
674    ) -> Condition:
675        """
676        AND this condition with one or multiple expressions.
677
678        Example:
679            >>> condition("x=1").and_("y=1").sql()
680            'x = 1 AND y = 1'
681
682        Args:
683            *expressions: the SQL code strings to parse.
684                If an `Expression` instance is passed, it will be used as-is.
685            dialect: the dialect used to parse the input expression.
686            copy: whether or not to copy the involved expressions (only applies to Expressions).
687            opts: other options to use to parse the input expressions.
688
689        Returns:
690            The new And condition.
691        """
692        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)
693
694    def or_(
695        self,
696        *expressions: t.Optional[ExpOrStr],
697        dialect: DialectType = None,
698        copy: bool = True,
699        **opts,
700    ) -> Condition:
701        """
702        OR this condition with one or multiple expressions.
703
704        Example:
705            >>> condition("x=1").or_("y=1").sql()
706            'x = 1 OR y = 1'
707
708        Args:
709            *expressions: the SQL code strings to parse.
710                If an `Expression` instance is passed, it will be used as-is.
711            dialect: the dialect used to parse the input expression.
712            copy: whether or not to copy the involved expressions (only applies to Expressions).
713            opts: other options to use to parse the input expressions.
714
715        Returns:
716            The new Or condition.
717        """
718        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)
719
720    def not_(self, copy: bool = True):
721        """
722        Wrap this condition with NOT.
723
724        Example:
725            >>> condition("x=1").not_().sql()
726            'NOT x = 1'
727
728        Args:
729            copy: whether or not to copy this object.
730
731        Returns:
732            The new Not instance.
733        """
734        return not_(self, copy=copy)
735
736    def as_(
737        self,
738        alias: str | Identifier,
739        quoted: t.Optional[bool] = None,
740        dialect: DialectType = None,
741        copy: bool = True,
742        **opts,
743    ) -> Alias:
744        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
745
746    def _binop(self, klass: t.Type[E], other: t.Any, reverse: bool = False) -> E:
747        this = self.copy()
748        other = convert(other, copy=True)
749        if not isinstance(this, klass) and not isinstance(other, klass):
750            this = _wrap(this, Binary)
751            other = _wrap(other, Binary)
752        if reverse:
753            return klass(this=other, expression=this)
754        return klass(this=this, expression=other)
755
756    def __getitem__(self, other: ExpOrStr | t.Tuple[ExpOrStr]):
757        return Bracket(
758            this=self.copy(), expressions=[convert(e, copy=True) for e in ensure_list(other)]
759        )
760
761    def isin(
762        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
763    ) -> In:
764        return In(
765            this=_maybe_copy(self, copy),
766            expressions=[convert(e, copy=copy) for e in expressions],
767            query=maybe_parse(query, copy=copy, **opts) if query else None,
768        )
769
770    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
771        return Between(
772            this=_maybe_copy(self, copy),
773            low=convert(low, copy=copy, **opts),
774            high=convert(high, copy=copy, **opts),
775        )
776
777    def is_(self, other: ExpOrStr) -> Is:
778        return self._binop(Is, other)
779
780    def like(self, other: ExpOrStr) -> Like:
781        return self._binop(Like, other)
782
783    def ilike(self, other: ExpOrStr) -> ILike:
784        return self._binop(ILike, other)
785
786    def eq(self, other: t.Any) -> EQ:
787        return self._binop(EQ, other)
788
789    def neq(self, other: t.Any) -> NEQ:
790        return self._binop(NEQ, other)
791
792    def rlike(self, other: ExpOrStr) -> RegexpLike:
793        return self._binop(RegexpLike, other)
794
795    def __lt__(self, other: t.Any) -> LT:
796        return self._binop(LT, other)
797
798    def __le__(self, other: t.Any) -> LTE:
799        return self._binop(LTE, other)
800
801    def __gt__(self, other: t.Any) -> GT:
802        return self._binop(GT, other)
803
804    def __ge__(self, other: t.Any) -> GTE:
805        return self._binop(GTE, other)
806
807    def __add__(self, other: t.Any) -> Add:
808        return self._binop(Add, other)
809
810    def __radd__(self, other: t.Any) -> Add:
811        return self._binop(Add, other, reverse=True)
812
813    def __sub__(self, other: t.Any) -> Sub:
814        return self._binop(Sub, other)
815
816    def __rsub__(self, other: t.Any) -> Sub:
817        return self._binop(Sub, other, reverse=True)
818
819    def __mul__(self, other: t.Any) -> Mul:
820        return self._binop(Mul, other)
821
822    def __rmul__(self, other: t.Any) -> Mul:
823        return self._binop(Mul, other, reverse=True)
824
825    def __truediv__(self, other: t.Any) -> Div:
826        return self._binop(Div, other)
827
828    def __rtruediv__(self, other: t.Any) -> Div:
829        return self._binop(Div, other, reverse=True)
830
831    def __floordiv__(self, other: t.Any) -> IntDiv:
832        return self._binop(IntDiv, other)
833
834    def __rfloordiv__(self, other: t.Any) -> IntDiv:
835        return self._binop(IntDiv, other, reverse=True)
836
837    def __mod__(self, other: t.Any) -> Mod:
838        return self._binop(Mod, other)
839
840    def __rmod__(self, other: t.Any) -> Mod:
841        return self._binop(Mod, other, reverse=True)
842
843    def __pow__(self, other: t.Any) -> Pow:
844        return self._binop(Pow, other)
845
846    def __rpow__(self, other: t.Any) -> Pow:
847        return self._binop(Pow, other, reverse=True)
848
849    def __and__(self, other: t.Any) -> And:
850        return self._binop(And, other)
851
852    def __rand__(self, other: t.Any) -> And:
853        return self._binop(And, other, reverse=True)
854
855    def __or__(self, other: t.Any) -> Or:
856        return self._binop(Or, other)
857
858    def __ror__(self, other: t.Any) -> Or:
859        return self._binop(Or, other, reverse=True)
860
861    def __neg__(self) -> Neg:
862        return Neg(this=_wrap(self.copy(), Binary))
863
864    def __invert__(self) -> Not:
865        return not_(self.copy())
def and_( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
668    def and_(
669        self,
670        *expressions: t.Optional[ExpOrStr],
671        dialect: DialectType = None,
672        copy: bool = True,
673        **opts,
674    ) -> Condition:
675        """
676        AND this condition with one or multiple expressions.
677
678        Example:
679            >>> condition("x=1").and_("y=1").sql()
680            'x = 1 AND y = 1'
681
682        Args:
683            *expressions: the SQL code strings to parse.
684                If an `Expression` instance is passed, it will be used as-is.
685            dialect: the dialect used to parse the input expression.
686            copy: whether or not to copy the involved expressions (only applies to Expressions).
687            opts: other options to use to parse the input expressions.
688
689        Returns:
690            The new And condition.
691        """
692        return and_(self, *expressions, dialect=dialect, copy=copy, **opts)

AND this condition with one or multiple expressions.

Example:
>>> condition("x=1").and_("y=1").sql()
'x = 1 AND y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new And condition.

def or_( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
694    def or_(
695        self,
696        *expressions: t.Optional[ExpOrStr],
697        dialect: DialectType = None,
698        copy: bool = True,
699        **opts,
700    ) -> Condition:
701        """
702        OR this condition with one or multiple expressions.
703
704        Example:
705            >>> condition("x=1").or_("y=1").sql()
706            'x = 1 OR y = 1'
707
708        Args:
709            *expressions: the SQL code strings to parse.
710                If an `Expression` instance is passed, it will be used as-is.
711            dialect: the dialect used to parse the input expression.
712            copy: whether or not to copy the involved expressions (only applies to Expressions).
713            opts: other options to use to parse the input expressions.
714
715        Returns:
716            The new Or condition.
717        """
718        return or_(self, *expressions, dialect=dialect, copy=copy, **opts)

OR this condition with one or multiple expressions.

Example:
>>> condition("x=1").or_("y=1").sql()
'x = 1 OR y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy the involved expressions (only applies to Expressions).
  • opts: other options to use to parse the input expressions.
Returns:

The new Or condition.

def not_(self, copy: bool = True):
720    def not_(self, copy: bool = True):
721        """
722        Wrap this condition with NOT.
723
724        Example:
725            >>> condition("x=1").not_().sql()
726            'NOT x = 1'
727
728        Args:
729            copy: whether or not to copy this object.
730
731        Returns:
732            The new Not instance.
733        """
734        return not_(self, copy=copy)

Wrap this condition with NOT.

Example:
>>> condition("x=1").not_().sql()
'NOT x = 1'
Arguments:
  • copy: whether or not to copy this object.
Returns:

The new Not instance.

def as_( self, alias: str | sqlglot.expressions.Identifier, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Alias:
736    def as_(
737        self,
738        alias: str | Identifier,
739        quoted: t.Optional[bool] = None,
740        dialect: DialectType = None,
741        copy: bool = True,
742        **opts,
743    ) -> Alias:
744        return alias_(self, alias, quoted=quoted, dialect=dialect, copy=copy, **opts)
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
761    def isin(
762        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
763    ) -> In:
764        return In(
765            this=_maybe_copy(self, copy),
766            expressions=[convert(e, copy=copy) for e in expressions],
767            query=maybe_parse(query, copy=copy, **opts) if query else None,
768        )
def between( self, low: Any, high: Any, copy: bool = True, **opts) -> sqlglot.expressions.Between:
770    def between(self, low: t.Any, high: t.Any, copy: bool = True, **opts) -> Between:
771        return Between(
772            this=_maybe_copy(self, copy),
773            low=convert(low, copy=copy, **opts),
774            high=convert(high, copy=copy, **opts),
775        )
def is_( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Is:
777    def is_(self, other: ExpOrStr) -> Is:
778        return self._binop(Is, other)
def like( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.Like:
780    def like(self, other: ExpOrStr) -> Like:
781        return self._binop(Like, other)
def ilike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.ILike:
783    def ilike(self, other: ExpOrStr) -> ILike:
784        return self._binop(ILike, other)
def eq(self, other: Any) -> sqlglot.expressions.EQ:
786    def eq(self, other: t.Any) -> EQ:
787        return self._binop(EQ, other)
def neq(self, other: Any) -> sqlglot.expressions.NEQ:
789    def neq(self, other: t.Any) -> NEQ:
790        return self._binop(NEQ, other)
def rlike( self, other: Union[str, sqlglot.expressions.Expression]) -> sqlglot.expressions.RegexpLike:
792    def rlike(self, other: ExpOrStr) -> RegexpLike:
793        return self._binop(RegexpLike, other)
key = 'condition'
class Predicate(Condition):
868class Predicate(Condition):
869    """Relationships like x = y, x > 1, x >= y."""

Relationships like x = y, x > 1, x >= y.

key = 'predicate'
class DerivedTable(Expression):
872class DerivedTable(Expression):
873    @property
874    def alias_column_names(self) -> t.List[str]:
875        table_alias = self.args.get("alias")
876        if not table_alias:
877            return []
878        return [c.name for c in table_alias.args.get("columns") or []]
879
880    @property
881    def selects(self):
882        return self.this.selects if isinstance(self.this, Subqueryable) else []
883
884    @property
885    def named_selects(self):
886        return [select.output_name for select in self.selects]
alias_column_names: List[str]
selects
named_selects
key = 'derivedtable'
class Unionable(Expression):
889class Unionable(Expression):
890    def union(
891        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
892    ) -> Unionable:
893        """
894        Builds a UNION expression.
895
896        Example:
897            >>> import sqlglot
898            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
899            'SELECT * FROM foo UNION SELECT * FROM bla'
900
901        Args:
902            expression: the SQL code string.
903                If an `Expression` instance is passed, it will be used as-is.
904            distinct: set the DISTINCT flag if and only if this is true.
905            dialect: the dialect used to parse the input expression.
906            opts: other options to use to parse the input expressions.
907
908        Returns:
909            The new Union expression.
910        """
911        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
912
913    def intersect(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds an INTERSECT expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
922            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Intersect expression.
933        """
934        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
935
936    def except_(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an EXCEPT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
945            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Except expression.
956        """
957        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)
def union( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
890    def union(
891        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
892    ) -> Unionable:
893        """
894        Builds a UNION expression.
895
896        Example:
897            >>> import sqlglot
898            >>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
899            'SELECT * FROM foo UNION SELECT * FROM bla'
900
901        Args:
902            expression: the SQL code string.
903                If an `Expression` instance is passed, it will be used as-is.
904            distinct: set the DISTINCT flag if and only if this is true.
905            dialect: the dialect used to parse the input expression.
906            opts: other options to use to parse the input expressions.
907
908        Returns:
909            The new Union expression.
910        """
911        return union(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds a UNION expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").union("SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union expression.

def intersect( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
913    def intersect(
914        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
915    ) -> Unionable:
916        """
917        Builds an INTERSECT expression.
918
919        Example:
920            >>> import sqlglot
921            >>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
922            'SELECT * FROM foo INTERSECT SELECT * FROM bla'
923
924        Args:
925            expression: the SQL code string.
926                If an `Expression` instance is passed, it will be used as-is.
927            distinct: set the DISTINCT flag if and only if this is true.
928            dialect: the dialect used to parse the input expression.
929            opts: other options to use to parse the input expressions.
930
931        Returns:
932            The new Intersect expression.
933        """
934        return intersect(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an INTERSECT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").intersect("SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect expression.

def except_( self, expression: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Unionable:
936    def except_(
937        self, expression: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
938    ) -> Unionable:
939        """
940        Builds an EXCEPT expression.
941
942        Example:
943            >>> import sqlglot
944            >>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
945            'SELECT * FROM foo EXCEPT SELECT * FROM bla'
946
947        Args:
948            expression: the SQL code string.
949                If an `Expression` instance is passed, it will be used as-is.
950            distinct: set the DISTINCT flag if and only if this is true.
951            dialect: the dialect used to parse the input expression.
952            opts: other options to use to parse the input expressions.
953
954        Returns:
955            The new Except expression.
956        """
957        return except_(left=self, right=expression, distinct=distinct, dialect=dialect, **opts)

Builds an EXCEPT expression.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("SELECT * FROM foo").except_("SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • expression: the SQL code string. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except expression.

key = 'unionable'
class UDTF(DerivedTable, Unionable):
960class UDTF(DerivedTable, Unionable):
961    @property
962    def selects(self):
963        alias = self.args.get("alias")
964        return alias.columns if alias else []
selects
key = 'udtf'
class Cache(Expression):
967class Cache(Expression):
968    arg_types = {
969        "with": False,
970        "this": True,
971        "lazy": False,
972        "options": False,
973        "expression": False,
974    }
arg_types = {'with': False, 'this': True, 'lazy': False, 'options': False, 'expression': False}
key = 'cache'
class Uncache(Expression):
977class Uncache(Expression):
978    arg_types = {"this": True, "exists": False}
arg_types = {'this': True, 'exists': False}
key = 'uncache'
class Create(Expression):
981class Create(Expression):
982    arg_types = {
983        "with": False,
984        "this": True,
985        "kind": True,
986        "expression": False,
987        "exists": False,
988        "properties": False,
989        "replace": False,
990        "unique": False,
991        "indexes": False,
992        "no_schema_binding": False,
993        "begin": False,
994        "clone": False,
995    }
arg_types = {'with': False, 'this': True, 'kind': True, 'expression': False, 'exists': False, 'properties': False, 'replace': False, 'unique': False, 'indexes': False, 'no_schema_binding': False, 'begin': False, 'clone': False}
key = 'create'
class Clone(Expression):
 999class Clone(Expression):
1000    arg_types = {
1001        "this": True,
1002        "when": False,
1003        "kind": False,
1004        "expression": False,
1005    }
arg_types = {'this': True, 'when': False, 'kind': False, 'expression': False}
key = 'clone'
class Describe(Expression):
1008class Describe(Expression):
1009    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'describe'
class Pragma(Expression):
1012class Pragma(Expression):
1013    pass
key = 'pragma'
class Set(Expression):
1016class Set(Expression):
1017    arg_types = {"expressions": False}
arg_types = {'expressions': False}
key = 'set'
class SetItem(Expression):
1020class SetItem(Expression):
1021    arg_types = {
1022        "this": False,
1023        "expressions": False,
1024        "kind": False,
1025        "collate": False,  # MySQL SET NAMES statement
1026        "global": False,
1027    }
arg_types = {'this': False, 'expressions': False, 'kind': False, 'collate': False, 'global': False}
key = 'setitem'
class Show(Expression):
1030class Show(Expression):
1031    arg_types = {
1032        "this": True,
1033        "target": False,
1034        "offset": False,
1035        "limit": False,
1036        "like": False,
1037        "where": False,
1038        "db": False,
1039        "full": False,
1040        "mutex": False,
1041        "query": False,
1042        "channel": False,
1043        "global": False,
1044        "log": False,
1045        "position": False,
1046        "types": False,
1047    }
arg_types = {'this': True, 'target': False, 'offset': False, 'limit': False, 'like': False, 'where': False, 'db': False, 'full': False, 'mutex': False, 'query': False, 'channel': False, 'global': False, 'log': False, 'position': False, 'types': False}
key = 'show'
class UserDefinedFunction(Expression):
1050class UserDefinedFunction(Expression):
1051    arg_types = {"this": True, "expressions": False, "wrapped": False}
arg_types = {'this': True, 'expressions': False, 'wrapped': False}
key = 'userdefinedfunction'
class CharacterSet(Expression):
1054class CharacterSet(Expression):
1055    arg_types = {"this": True, "default": False}
arg_types = {'this': True, 'default': False}
key = 'characterset'
class With(Expression):
1058class With(Expression):
1059    arg_types = {"expressions": True, "recursive": False}
1060
1061    @property
1062    def recursive(self) -> bool:
1063        return bool(self.args.get("recursive"))
arg_types = {'expressions': True, 'recursive': False}
recursive: bool
key = 'with'
class WithinGroup(Expression):
1066class WithinGroup(Expression):
1067    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'withingroup'
class CTE(DerivedTable):
1070class CTE(DerivedTable):
1071    arg_types = {"this": True, "alias": True}
arg_types = {'this': True, 'alias': True}
key = 'cte'
class TableAlias(Expression):
1074class TableAlias(Expression):
1075    arg_types = {"this": False, "columns": False}
1076
1077    @property
1078    def columns(self):
1079        return self.args.get("columns") or []
arg_types = {'this': False, 'columns': False}
columns
key = 'tablealias'
class BitString(Condition):
1082class BitString(Condition):
1083    pass
key = 'bitstring'
class HexString(Condition):
1086class HexString(Condition):
1087    pass
key = 'hexstring'
class ByteString(Condition):
1090class ByteString(Condition):
1091    pass
key = 'bytestring'
class RawString(Condition):
1094class RawString(Condition):
1095    pass
key = 'rawstring'
class Column(Condition):
1098class Column(Condition):
1099    arg_types = {"this": True, "table": False, "db": False, "catalog": False, "join_mark": False}
1100
1101    @property
1102    def table(self) -> str:
1103        return self.text("table")
1104
1105    @property
1106    def db(self) -> str:
1107        return self.text("db")
1108
1109    @property
1110    def catalog(self) -> str:
1111        return self.text("catalog")
1112
1113    @property
1114    def output_name(self) -> str:
1115        return self.name
1116
1117    @property
1118    def parts(self) -> t.List[Identifier]:
1119        """Return the parts of a column in order catalog, db, table, name."""
1120        return [
1121            t.cast(Identifier, self.args[part])
1122            for part in ("catalog", "db", "table", "this")
1123            if self.args.get(part)
1124        ]
1125
1126    def to_dot(self) -> Dot:
1127        """Converts the column into a dot expression."""
1128        parts = self.parts
1129        parent = self.parent
1130
1131        while parent:
1132            if isinstance(parent, Dot):
1133                parts.append(parent.expression)
1134            parent = parent.parent
1135
1136        return Dot.build(parts)
arg_types = {'this': True, 'table': False, 'db': False, 'catalog': False, 'join_mark': False}
table: str
db: str
catalog: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''

Return the parts of a column in order catalog, db, table, name.

def to_dot(self) -> sqlglot.expressions.Dot:
1126    def to_dot(self) -> Dot:
1127        """Converts the column into a dot expression."""
1128        parts = self.parts
1129        parent = self.parent
1130
1131        while parent:
1132            if isinstance(parent, Dot):
1133                parts.append(parent.expression)
1134            parent = parent.parent
1135
1136        return Dot.build(parts)

Converts the column into a dot expression.

key = 'column'
class ColumnPosition(Expression):
1139class ColumnPosition(Expression):
1140    arg_types = {"this": False, "position": True}
arg_types = {'this': False, 'position': True}
key = 'columnposition'
class ColumnDef(Expression):
1143class ColumnDef(Expression):
1144    arg_types = {
1145        "this": True,
1146        "kind": False,
1147        "constraints": False,
1148        "exists": False,
1149        "position": False,
1150    }
1151
1152    @property
1153    def constraints(self) -> t.List[ColumnConstraint]:
1154        return self.args.get("constraints") or []
arg_types = {'this': True, 'kind': False, 'constraints': False, 'exists': False, 'position': False}
key = 'columndef'
class AlterColumn(Expression):
1157class AlterColumn(Expression):
1158    arg_types = {
1159        "this": True,
1160        "dtype": False,
1161        "collate": False,
1162        "using": False,
1163        "default": False,
1164        "drop": False,
1165    }
arg_types = {'this': True, 'dtype': False, 'collate': False, 'using': False, 'default': False, 'drop': False}
key = 'altercolumn'
class RenameTable(Expression):
1168class RenameTable(Expression):
1169    pass
key = 'renametable'
class SetTag(Expression):
1172class SetTag(Expression):
1173    arg_types = {"expressions": True, "unset": False}
arg_types = {'expressions': True, 'unset': False}
key = 'settag'
class Comment(Expression):
1176class Comment(Expression):
1177    arg_types = {"this": True, "kind": True, "expression": True, "exists": False}
arg_types = {'this': True, 'kind': True, 'expression': True, 'exists': False}
key = 'comment'
class MergeTreeTTLAction(Expression):
1181class MergeTreeTTLAction(Expression):
1182    arg_types = {
1183        "this": True,
1184        "delete": False,
1185        "recompress": False,
1186        "to_disk": False,
1187        "to_volume": False,
1188    }
arg_types = {'this': True, 'delete': False, 'recompress': False, 'to_disk': False, 'to_volume': False}
key = 'mergetreettlaction'
class MergeTreeTTL(Expression):
1192class MergeTreeTTL(Expression):
1193    arg_types = {
1194        "expressions": True,
1195        "where": False,
1196        "group": False,
1197        "aggregates": False,
1198    }
arg_types = {'expressions': True, 'where': False, 'group': False, 'aggregates': False}
key = 'mergetreettl'
class ColumnConstraint(Expression):
1201class ColumnConstraint(Expression):
1202    arg_types = {"this": False, "kind": True}
1203
1204    @property
1205    def kind(self) -> ColumnConstraintKind:
1206        return self.args["kind"]
arg_types = {'this': False, 'kind': True}
key = 'columnconstraint'
class ColumnConstraintKind(Expression):
1209class ColumnConstraintKind(Expression):
1210    pass
key = 'columnconstraintkind'
class AutoIncrementColumnConstraint(ColumnConstraintKind):
1213class AutoIncrementColumnConstraint(ColumnConstraintKind):
1214    pass
key = 'autoincrementcolumnconstraint'
class CaseSpecificColumnConstraint(ColumnConstraintKind):
1217class CaseSpecificColumnConstraint(ColumnConstraintKind):
1218    arg_types = {"not_": True}
arg_types = {'not_': True}
key = 'casespecificcolumnconstraint'
class CharacterSetColumnConstraint(ColumnConstraintKind):
1221class CharacterSetColumnConstraint(ColumnConstraintKind):
1222    arg_types = {"this": True}
arg_types = {'this': True}
key = 'charactersetcolumnconstraint'
class CheckColumnConstraint(ColumnConstraintKind):
1225class CheckColumnConstraint(ColumnConstraintKind):
1226    pass
key = 'checkcolumnconstraint'
class CollateColumnConstraint(ColumnConstraintKind):
1229class CollateColumnConstraint(ColumnConstraintKind):
1230    pass
key = 'collatecolumnconstraint'
class CommentColumnConstraint(ColumnConstraintKind):
1233class CommentColumnConstraint(ColumnConstraintKind):
1234    pass
key = 'commentcolumnconstraint'
class CompressColumnConstraint(ColumnConstraintKind):
1237class CompressColumnConstraint(ColumnConstraintKind):
1238    pass
key = 'compresscolumnconstraint'
class DateFormatColumnConstraint(ColumnConstraintKind):
1241class DateFormatColumnConstraint(ColumnConstraintKind):
1242    arg_types = {"this": True}
arg_types = {'this': True}
key = 'dateformatcolumnconstraint'
class DefaultColumnConstraint(ColumnConstraintKind):
1245class DefaultColumnConstraint(ColumnConstraintKind):
1246    pass
key = 'defaultcolumnconstraint'
class EncodeColumnConstraint(ColumnConstraintKind):
1249class EncodeColumnConstraint(ColumnConstraintKind):
1250    pass
key = 'encodecolumnconstraint'
class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1253class GeneratedAsIdentityColumnConstraint(ColumnConstraintKind):
1254    # this: True -> ALWAYS, this: False -> BY DEFAULT
1255    arg_types = {
1256        "this": False,
1257        "expression": False,
1258        "on_null": False,
1259        "start": False,
1260        "increment": False,
1261        "minvalue": False,
1262        "maxvalue": False,
1263        "cycle": False,
1264    }
arg_types = {'this': False, 'expression': False, 'on_null': False, 'start': False, 'increment': False, 'minvalue': False, 'maxvalue': False, 'cycle': False}
key = 'generatedasidentitycolumnconstraint'
class InlineLengthColumnConstraint(ColumnConstraintKind):
1267class InlineLengthColumnConstraint(ColumnConstraintKind):
1268    pass
key = 'inlinelengthcolumnconstraint'
class NotNullColumnConstraint(ColumnConstraintKind):
1271class NotNullColumnConstraint(ColumnConstraintKind):
1272    arg_types = {"allow_null": False}
arg_types = {'allow_null': False}
key = 'notnullcolumnconstraint'
class OnUpdateColumnConstraint(ColumnConstraintKind):
1276class OnUpdateColumnConstraint(ColumnConstraintKind):
1277    pass
key = 'onupdatecolumnconstraint'
class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1280class PrimaryKeyColumnConstraint(ColumnConstraintKind):
1281    arg_types = {"desc": False}
arg_types = {'desc': False}
key = 'primarykeycolumnconstraint'
class TitleColumnConstraint(ColumnConstraintKind):
1284class TitleColumnConstraint(ColumnConstraintKind):
1285    pass
key = 'titlecolumnconstraint'
class UniqueColumnConstraint(ColumnConstraintKind):
1288class UniqueColumnConstraint(ColumnConstraintKind):
1289    arg_types = {"this": False}
arg_types = {'this': False}
key = 'uniquecolumnconstraint'
class UppercaseColumnConstraint(ColumnConstraintKind):
1292class UppercaseColumnConstraint(ColumnConstraintKind):
1293    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'uppercasecolumnconstraint'
class PathColumnConstraint(ColumnConstraintKind):
1296class PathColumnConstraint(ColumnConstraintKind):
1297    pass
key = 'pathcolumnconstraint'
class Constraint(Expression):
1300class Constraint(Expression):
1301    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'constraint'
class Delete(Expression):
1304class Delete(Expression):
1305    arg_types = {
1306        "with": False,
1307        "this": False,
1308        "using": False,
1309        "where": False,
1310        "returning": False,
1311        "limit": False,
1312    }
1313
1314    def delete(
1315        self,
1316        table: ExpOrStr,
1317        dialect: DialectType = None,
1318        copy: bool = True,
1319        **opts,
1320    ) -> Delete:
1321        """
1322        Create a DELETE expression or replace the table on an existing DELETE expression.
1323
1324        Example:
1325            >>> delete("tbl").sql()
1326            'DELETE FROM tbl'
1327
1328        Args:
1329            table: the table from which to delete.
1330            dialect: the dialect used to parse the input expression.
1331            copy: if `False`, modify this expression instance in-place.
1332            opts: other options to use to parse the input expressions.
1333
1334        Returns:
1335            Delete: the modified expression.
1336        """
1337        return _apply_builder(
1338            expression=table,
1339            instance=self,
1340            arg="this",
1341            dialect=dialect,
1342            into=Table,
1343            copy=copy,
1344            **opts,
1345        )
1346
1347    def where(
1348        self,
1349        *expressions: t.Optional[ExpOrStr],
1350        append: bool = True,
1351        dialect: DialectType = None,
1352        copy: bool = True,
1353        **opts,
1354    ) -> Delete:
1355        """
1356        Append to or set the WHERE expressions.
1357
1358        Example:
1359            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1360            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1361
1362        Args:
1363            *expressions: the SQL code strings to parse.
1364                If an `Expression` instance is passed, it will be used as-is.
1365                Multiple expressions are combined with an AND operator.
1366            append: if `True`, AND the new expressions to any existing expression.
1367                Otherwise, this resets the expression.
1368            dialect: the dialect used to parse the input expressions.
1369            copy: if `False`, modify this expression instance in-place.
1370            opts: other options to use to parse the input expressions.
1371
1372        Returns:
1373            Delete: the modified expression.
1374        """
1375        return _apply_conjunction_builder(
1376            *expressions,
1377            instance=self,
1378            arg="where",
1379            append=append,
1380            into=Where,
1381            dialect=dialect,
1382            copy=copy,
1383            **opts,
1384        )
1385
1386    def returning(
1387        self,
1388        expression: ExpOrStr,
1389        dialect: DialectType = None,
1390        copy: bool = True,
1391        **opts,
1392    ) -> Delete:
1393        """
1394        Set the RETURNING expression. Not supported by all dialects.
1395
1396        Example:
1397            >>> delete("tbl").returning("*", dialect="postgres").sql()
1398            'DELETE FROM tbl RETURNING *'
1399
1400        Args:
1401            expression: the SQL code strings to parse.
1402                If an `Expression` instance is passed, it will be used as-is.
1403            dialect: the dialect used to parse the input expressions.
1404            copy: if `False`, modify this expression instance in-place.
1405            opts: other options to use to parse the input expressions.
1406
1407        Returns:
1408            Delete: the modified expression.
1409        """
1410        return _apply_builder(
1411            expression=expression,
1412            instance=self,
1413            arg="returning",
1414            prefix="RETURNING",
1415            dialect=dialect,
1416            copy=copy,
1417            into=Returning,
1418            **opts,
1419        )
arg_types = {'with': False, 'this': False, 'using': False, 'where': False, 'returning': False, 'limit': False}
def delete( self, table: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1314    def delete(
1315        self,
1316        table: ExpOrStr,
1317        dialect: DialectType = None,
1318        copy: bool = True,
1319        **opts,
1320    ) -> Delete:
1321        """
1322        Create a DELETE expression or replace the table on an existing DELETE expression.
1323
1324        Example:
1325            >>> delete("tbl").sql()
1326            'DELETE FROM tbl'
1327
1328        Args:
1329            table: the table from which to delete.
1330            dialect: the dialect used to parse the input expression.
1331            copy: if `False`, modify this expression instance in-place.
1332            opts: other options to use to parse the input expressions.
1333
1334        Returns:
1335            Delete: the modified expression.
1336        """
1337        return _apply_builder(
1338            expression=table,
1339            instance=self,
1340            arg="this",
1341            dialect=dialect,
1342            into=Table,
1343            copy=copy,
1344            **opts,
1345        )

Create a DELETE expression or replace the table on an existing DELETE expression.

Example:
>>> delete("tbl").sql()
'DELETE FROM tbl'
Arguments:
  • table: the table from which to delete.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1347    def where(
1348        self,
1349        *expressions: t.Optional[ExpOrStr],
1350        append: bool = True,
1351        dialect: DialectType = None,
1352        copy: bool = True,
1353        **opts,
1354    ) -> Delete:
1355        """
1356        Append to or set the WHERE expressions.
1357
1358        Example:
1359            >>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
1360            "DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
1361
1362        Args:
1363            *expressions: the SQL code strings to parse.
1364                If an `Expression` instance is passed, it will be used as-is.
1365                Multiple expressions are combined with an AND operator.
1366            append: if `True`, AND the new expressions to any existing expression.
1367                Otherwise, this resets the expression.
1368            dialect: the dialect used to parse the input expressions.
1369            copy: if `False`, modify this expression instance in-place.
1370            opts: other options to use to parse the input expressions.
1371
1372        Returns:
1373            Delete: the modified expression.
1374        """
1375        return _apply_conjunction_builder(
1376            *expressions,
1377            instance=self,
1378            arg="where",
1379            append=append,
1380            into=Where,
1381            dialect=dialect,
1382            copy=copy,
1383            **opts,
1384        )

Append to or set the WHERE expressions.

Example:
>>> delete("tbl").where("x = 'a' OR x < 'b'").sql()
"DELETE FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

def returning( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Delete:
1386    def returning(
1387        self,
1388        expression: ExpOrStr,
1389        dialect: DialectType = None,
1390        copy: bool = True,
1391        **opts,
1392    ) -> Delete:
1393        """
1394        Set the RETURNING expression. Not supported by all dialects.
1395
1396        Example:
1397            >>> delete("tbl").returning("*", dialect="postgres").sql()
1398            'DELETE FROM tbl RETURNING *'
1399
1400        Args:
1401            expression: the SQL code strings to parse.
1402                If an `Expression` instance is passed, it will be used as-is.
1403            dialect: the dialect used to parse the input expressions.
1404            copy: if `False`, modify this expression instance in-place.
1405            opts: other options to use to parse the input expressions.
1406
1407        Returns:
1408            Delete: the modified expression.
1409        """
1410        return _apply_builder(
1411            expression=expression,
1412            instance=self,
1413            arg="returning",
1414            prefix="RETURNING",
1415            dialect=dialect,
1416            copy=copy,
1417            into=Returning,
1418            **opts,
1419        )

Set the RETURNING expression. Not supported by all dialects.

Example:
>>> delete("tbl").returning("*", dialect="postgres").sql()
'DELETE FROM tbl RETURNING *'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Delete: the modified expression.

key = 'delete'
class Drop(Expression):
1422class Drop(Expression):
1423    arg_types = {
1424        "this": False,
1425        "kind": False,
1426        "exists": False,
1427        "temporary": False,
1428        "materialized": False,
1429        "cascade": False,
1430        "constraints": False,
1431        "purge": False,
1432    }
arg_types = {'this': False, 'kind': False, 'exists': False, 'temporary': False, 'materialized': False, 'cascade': False, 'constraints': False, 'purge': False}
key = 'drop'
class Filter(Expression):
1435class Filter(Expression):
1436    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'filter'
class Check(Expression):
1439class Check(Expression):
1440    pass
key = 'check'
class Directory(Expression):
1443class Directory(Expression):
1444    # https://spark.apache.org/docs/3.0.0-preview/sql-ref-syntax-dml-insert-overwrite-directory-hive.html
1445    arg_types = {"this": True, "local": False, "row_format": False}
arg_types = {'this': True, 'local': False, 'row_format': False}
key = 'directory'
class ForeignKey(Expression):
1448class ForeignKey(Expression):
1449    arg_types = {
1450        "expressions": True,
1451        "reference": False,
1452        "delete": False,
1453        "update": False,
1454    }
arg_types = {'expressions': True, 'reference': False, 'delete': False, 'update': False}
key = 'foreignkey'
class PrimaryKey(Expression):
1457class PrimaryKey(Expression):
1458    arg_types = {"expressions": True, "options": False}
arg_types = {'expressions': True, 'options': False}
key = 'primarykey'
class Into(Expression):
1463class Into(Expression):
1464    arg_types = {"this": True, "temporary": False, "unlogged": False}
arg_types = {'this': True, 'temporary': False, 'unlogged': False}
key = 'into'
class From(Expression):
1467class From(Expression):
1468    @property
1469    def name(self) -> str:
1470        return self.this.name
1471
1472    @property
1473    def alias_or_name(self) -> str:
1474        return self.this.alias_or_name
name: str
alias_or_name: str
key = 'from'
class Having(Expression):
1477class Having(Expression):
1478    pass
key = 'having'
class Hint(Expression):
1481class Hint(Expression):
1482    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'hint'
class JoinHint(Expression):
1485class JoinHint(Expression):
1486    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'joinhint'
class Identifier(Expression):
1489class Identifier(Expression):
1490    arg_types = {"this": True, "quoted": False}
1491
1492    @property
1493    def quoted(self) -> bool:
1494        return bool(self.args.get("quoted"))
1495
1496    @property
1497    def hashable_args(self) -> t.Any:
1498        if self.quoted and any(char.isupper() for char in self.this):
1499            return (self.this, self.quoted)
1500        return self.this.lower()
1501
1502    @property
1503    def output_name(self) -> str:
1504        return self.name
arg_types = {'this': True, 'quoted': False}
quoted: bool
hashable_args: Any
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'identifier'
class Index(Expression):
1507class Index(Expression):
1508    arg_types = {
1509        "this": False,
1510        "table": False,
1511        "using": False,
1512        "where": False,
1513        "columns": False,
1514        "unique": False,
1515        "primary": False,
1516        "amp": False,  # teradata
1517        "partition_by": False,  # teradata
1518    }
arg_types = {'this': False, 'table': False, 'using': False, 'where': False, 'columns': False, 'unique': False, 'primary': False, 'amp': False, 'partition_by': False}
key = 'index'
class Insert(Expression):
1521class Insert(Expression):
1522    arg_types = {
1523        "with": False,
1524        "this": True,
1525        "expression": False,
1526        "conflict": False,
1527        "returning": False,
1528        "overwrite": False,
1529        "exists": False,
1530        "partition": False,
1531        "alternative": False,
1532    }
1533
1534    def with_(
1535        self,
1536        alias: ExpOrStr,
1537        as_: ExpOrStr,
1538        recursive: t.Optional[bool] = None,
1539        append: bool = True,
1540        dialect: DialectType = None,
1541        copy: bool = True,
1542        **opts,
1543    ) -> Insert:
1544        """
1545        Append to or set the common table expressions.
1546
1547        Example:
1548            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1549            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1550
1551        Args:
1552            alias: the SQL code string to parse as the table name.
1553                If an `Expression` instance is passed, this is used as-is.
1554            as_: the SQL code string to parse as the table expression.
1555                If an `Expression` instance is passed, it will be used as-is.
1556            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1557            append: if `True`, add to any existing expressions.
1558                Otherwise, this resets the expressions.
1559            dialect: the dialect used to parse the input expression.
1560            copy: if `False`, modify this expression instance in-place.
1561            opts: other options to use to parse the input expressions.
1562
1563        Returns:
1564            The modified expression.
1565        """
1566        return _apply_cte_builder(
1567            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1568        )
arg_types = {'with': False, 'this': True, 'expression': False, 'conflict': False, 'returning': False, 'overwrite': False, 'exists': False, 'partition': False, 'alternative': False}
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
1534    def with_(
1535        self,
1536        alias: ExpOrStr,
1537        as_: ExpOrStr,
1538        recursive: t.Optional[bool] = None,
1539        append: bool = True,
1540        dialect: DialectType = None,
1541        copy: bool = True,
1542        **opts,
1543    ) -> Insert:
1544        """
1545        Append to or set the common table expressions.
1546
1547        Example:
1548            >>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
1549            'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
1550
1551        Args:
1552            alias: the SQL code string to parse as the table name.
1553                If an `Expression` instance is passed, this is used as-is.
1554            as_: the SQL code string to parse as the table expression.
1555                If an `Expression` instance is passed, it will be used as-is.
1556            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
1557            append: if `True`, add to any existing expressions.
1558                Otherwise, this resets the expressions.
1559            dialect: the dialect used to parse the input expression.
1560            copy: if `False`, modify this expression instance in-place.
1561            opts: other options to use to parse the input expressions.
1562
1563        Returns:
1564            The modified expression.
1565        """
1566        return _apply_cte_builder(
1567            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
1568        )

Append to or set the common table expressions.

Example:
>>> insert("SELECT x FROM cte", "t").with_("cte", as_="SELECT * FROM tbl").sql()
'WITH cte AS (SELECT * FROM tbl) INSERT INTO t SELECT x FROM cte'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'insert'
class OnConflict(Expression):
1571class OnConflict(Expression):
1572    arg_types = {
1573        "duplicate": False,
1574        "expressions": False,
1575        "nothing": False,
1576        "key": False,
1577        "constraint": False,
1578    }
arg_types = {'duplicate': False, 'expressions': False, 'nothing': False, 'key': False, 'constraint': False}
key = 'onconflict'
class Returning(Expression):
1581class Returning(Expression):
1582    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'returning'
class Introducer(Expression):
1586class Introducer(Expression):
1587    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'introducer'
class National(Expression):
1591class National(Expression):
1592    pass
key = 'national'
class LoadData(Expression):
1595class LoadData(Expression):
1596    arg_types = {
1597        "this": True,
1598        "local": False,
1599        "overwrite": False,
1600        "inpath": True,
1601        "partition": False,
1602        "input_format": False,
1603        "serde": False,
1604    }
arg_types = {'this': True, 'local': False, 'overwrite': False, 'inpath': True, 'partition': False, 'input_format': False, 'serde': False}
key = 'loaddata'
class Partition(Expression):
1607class Partition(Expression):
1608    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'partition'
class Fetch(Expression):
1611class Fetch(Expression):
1612    arg_types = {
1613        "direction": False,
1614        "count": False,
1615        "percent": False,
1616        "with_ties": False,
1617    }
arg_types = {'direction': False, 'count': False, 'percent': False, 'with_ties': False}
key = 'fetch'
class Group(Expression):
1620class Group(Expression):
1621    arg_types = {
1622        "expressions": False,
1623        "grouping_sets": False,
1624        "cube": False,
1625        "rollup": False,
1626        "totals": False,
1627    }
arg_types = {'expressions': False, 'grouping_sets': False, 'cube': False, 'rollup': False, 'totals': False}
key = 'group'
class Lambda(Expression):
1630class Lambda(Expression):
1631    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'lambda'
class Limit(Expression):
1634class Limit(Expression):
1635    arg_types = {"this": False, "expression": True, "offset": False}
arg_types = {'this': False, 'expression': True, 'offset': False}
key = 'limit'
class Literal(Condition):
1638class Literal(Condition):
1639    arg_types = {"this": True, "is_string": True}
1640
1641    @property
1642    def hashable_args(self) -> t.Any:
1643        return (self.this, self.args.get("is_string"))
1644
1645    @classmethod
1646    def number(cls, number) -> Literal:
1647        return cls(this=str(number), is_string=False)
1648
1649    @classmethod
1650    def string(cls, string) -> Literal:
1651        return cls(this=str(string), is_string=True)
1652
1653    @property
1654    def output_name(self) -> str:
1655        return self.name
arg_types = {'this': True, 'is_string': True}
hashable_args: Any
@classmethod
def number(cls, number) -> sqlglot.expressions.Literal:
1645    @classmethod
1646    def number(cls, number) -> Literal:
1647        return cls(this=str(number), is_string=False)
@classmethod
def string(cls, string) -> sqlglot.expressions.Literal:
1649    @classmethod
1650    def string(cls, string) -> Literal:
1651        return cls(this=str(string), is_string=True)
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'literal'
class Join(Expression):
1658class Join(Expression):
1659    arg_types = {
1660        "this": True,
1661        "on": False,
1662        "side": False,
1663        "kind": False,
1664        "using": False,
1665        "method": False,
1666        "global": False,
1667        "hint": False,
1668    }
1669
1670    @property
1671    def method(self) -> str:
1672        return self.text("method").upper()
1673
1674    @property
1675    def kind(self) -> str:
1676        return self.text("kind").upper()
1677
1678    @property
1679    def side(self) -> str:
1680        return self.text("side").upper()
1681
1682    @property
1683    def hint(self) -> str:
1684        return self.text("hint").upper()
1685
1686    @property
1687    def alias_or_name(self) -> str:
1688        return self.this.alias_or_name
1689
1690    def on(
1691        self,
1692        *expressions: t.Optional[ExpOrStr],
1693        append: bool = True,
1694        dialect: DialectType = None,
1695        copy: bool = True,
1696        **opts,
1697    ) -> Join:
1698        """
1699        Append to or set the ON expressions.
1700
1701        Example:
1702            >>> import sqlglot
1703            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1704            'JOIN x ON y = 1'
1705
1706        Args:
1707            *expressions: the SQL code strings to parse.
1708                If an `Expression` instance is passed, it will be used as-is.
1709                Multiple expressions are combined with an AND operator.
1710            append: if `True`, AND the new expressions to any existing expression.
1711                Otherwise, this resets the expression.
1712            dialect: the dialect used to parse the input expressions.
1713            copy: if `False`, modify this expression instance in-place.
1714            opts: other options to use to parse the input expressions.
1715
1716        Returns:
1717            The modified Join expression.
1718        """
1719        join = _apply_conjunction_builder(
1720            *expressions,
1721            instance=self,
1722            arg="on",
1723            append=append,
1724            dialect=dialect,
1725            copy=copy,
1726            **opts,
1727        )
1728
1729        if join.kind == "CROSS":
1730            join.set("kind", None)
1731
1732        return join
1733
1734    def using(
1735        self,
1736        *expressions: t.Optional[ExpOrStr],
1737        append: bool = True,
1738        dialect: DialectType = None,
1739        copy: bool = True,
1740        **opts,
1741    ) -> Join:
1742        """
1743        Append to or set the USING expressions.
1744
1745        Example:
1746            >>> import sqlglot
1747            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1748            'JOIN x USING (foo, bla)'
1749
1750        Args:
1751            *expressions: the SQL code strings to parse.
1752                If an `Expression` instance is passed, it will be used as-is.
1753            append: if `True`, concatenate the new expressions to the existing "using" list.
1754                Otherwise, this resets the expression.
1755            dialect: the dialect used to parse the input expressions.
1756            copy: if `False`, modify this expression instance in-place.
1757            opts: other options to use to parse the input expressions.
1758
1759        Returns:
1760            The modified Join expression.
1761        """
1762        join = _apply_list_builder(
1763            *expressions,
1764            instance=self,
1765            arg="using",
1766            append=append,
1767            dialect=dialect,
1768            copy=copy,
1769            **opts,
1770        )
1771
1772        if join.kind == "CROSS":
1773            join.set("kind", None)
1774
1775        return join
arg_types = {'this': True, 'on': False, 'side': False, 'kind': False, 'using': False, 'method': False, 'global': False, 'hint': False}
method: str
kind: str
side: str
hint: str
alias_or_name: str
def on( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1690    def on(
1691        self,
1692        *expressions: t.Optional[ExpOrStr],
1693        append: bool = True,
1694        dialect: DialectType = None,
1695        copy: bool = True,
1696        **opts,
1697    ) -> Join:
1698        """
1699        Append to or set the ON expressions.
1700
1701        Example:
1702            >>> import sqlglot
1703            >>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
1704            'JOIN x ON y = 1'
1705
1706        Args:
1707            *expressions: the SQL code strings to parse.
1708                If an `Expression` instance is passed, it will be used as-is.
1709                Multiple expressions are combined with an AND operator.
1710            append: if `True`, AND the new expressions to any existing expression.
1711                Otherwise, this resets the expression.
1712            dialect: the dialect used to parse the input expressions.
1713            copy: if `False`, modify this expression instance in-place.
1714            opts: other options to use to parse the input expressions.
1715
1716        Returns:
1717            The modified Join expression.
1718        """
1719        join = _apply_conjunction_builder(
1720            *expressions,
1721            instance=self,
1722            arg="on",
1723            append=append,
1724            dialect=dialect,
1725            copy=copy,
1726            **opts,
1727        )
1728
1729        if join.kind == "CROSS":
1730            join.set("kind", None)
1731
1732        return join

Append to or set the ON expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).on("y = 1").sql()
'JOIN x ON y = 1'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

def using( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Join:
1734    def using(
1735        self,
1736        *expressions: t.Optional[ExpOrStr],
1737        append: bool = True,
1738        dialect: DialectType = None,
1739        copy: bool = True,
1740        **opts,
1741    ) -> Join:
1742        """
1743        Append to or set the USING expressions.
1744
1745        Example:
1746            >>> import sqlglot
1747            >>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
1748            'JOIN x USING (foo, bla)'
1749
1750        Args:
1751            *expressions: the SQL code strings to parse.
1752                If an `Expression` instance is passed, it will be used as-is.
1753            append: if `True`, concatenate the new expressions to the existing "using" list.
1754                Otherwise, this resets the expression.
1755            dialect: the dialect used to parse the input expressions.
1756            copy: if `False`, modify this expression instance in-place.
1757            opts: other options to use to parse the input expressions.
1758
1759        Returns:
1760            The modified Join expression.
1761        """
1762        join = _apply_list_builder(
1763            *expressions,
1764            instance=self,
1765            arg="using",
1766            append=append,
1767            dialect=dialect,
1768            copy=copy,
1769            **opts,
1770        )
1771
1772        if join.kind == "CROSS":
1773            join.set("kind", None)
1774
1775        return join

Append to or set the USING expressions.

Example:
>>> import sqlglot
>>> sqlglot.parse_one("JOIN x", into=Join).using("foo", "bla").sql()
'JOIN x USING (foo, bla)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, concatenate the new expressions to the existing "using" list. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Join expression.

key = 'join'
class Lateral(UDTF):
1778class Lateral(UDTF):
1779    arg_types = {"this": True, "view": False, "outer": False, "alias": False}
arg_types = {'this': True, 'view': False, 'outer': False, 'alias': False}
key = 'lateral'
class MatchRecognize(Expression):
1782class MatchRecognize(Expression):
1783    arg_types = {
1784        "partition_by": False,
1785        "order": False,
1786        "measures": False,
1787        "rows": False,
1788        "after": False,
1789        "pattern": False,
1790        "define": False,
1791        "alias": False,
1792    }
arg_types = {'partition_by': False, 'order': False, 'measures': False, 'rows': False, 'after': False, 'pattern': False, 'define': False, 'alias': False}
key = 'matchrecognize'
class Final(Expression):
1797class Final(Expression):
1798    pass
key = 'final'
class Offset(Expression):
1801class Offset(Expression):
1802    arg_types = {"this": False, "expression": True}
arg_types = {'this': False, 'expression': True}
key = 'offset'
class Order(Expression):
1805class Order(Expression):
1806    arg_types = {"this": False, "expressions": True}
arg_types = {'this': False, 'expressions': True}
key = 'order'
class Cluster(Order):
1811class Cluster(Order):
1812    pass
key = 'cluster'
class Distribute(Order):
1815class Distribute(Order):
1816    pass
key = 'distribute'
class Sort(Order):
1819class Sort(Order):
1820    pass
key = 'sort'
class Ordered(Expression):
1823class Ordered(Expression):
1824    arg_types = {"this": True, "desc": True, "nulls_first": True}
arg_types = {'this': True, 'desc': True, 'nulls_first': True}
key = 'ordered'
class Property(Expression):
1827class Property(Expression):
1828    arg_types = {"this": True, "value": True}
arg_types = {'this': True, 'value': True}
key = 'property'
class AlgorithmProperty(Property):
1831class AlgorithmProperty(Property):
1832    arg_types = {"this": True}
arg_types = {'this': True}
key = 'algorithmproperty'
class AutoIncrementProperty(Property):
1835class AutoIncrementProperty(Property):
1836    arg_types = {"this": True}
arg_types = {'this': True}
key = 'autoincrementproperty'
class BlockCompressionProperty(Property):
1839class BlockCompressionProperty(Property):
1840    arg_types = {"autotemp": False, "always": False, "default": True, "manual": True, "never": True}
arg_types = {'autotemp': False, 'always': False, 'default': True, 'manual': True, 'never': True}
key = 'blockcompressionproperty'
class CharacterSetProperty(Property):
1843class CharacterSetProperty(Property):
1844    arg_types = {"this": True, "default": True}
arg_types = {'this': True, 'default': True}
key = 'charactersetproperty'
class ChecksumProperty(Property):
1847class ChecksumProperty(Property):
1848    arg_types = {"on": False, "default": False}
arg_types = {'on': False, 'default': False}
key = 'checksumproperty'
class CollateProperty(Property):
1851class CollateProperty(Property):
1852    arg_types = {"this": True}
arg_types = {'this': True}
key = 'collateproperty'
class CopyGrantsProperty(Property):
1855class CopyGrantsProperty(Property):
1856    arg_types = {}
arg_types = {}
key = 'copygrantsproperty'
class DataBlocksizeProperty(Property):
1859class DataBlocksizeProperty(Property):
1860    arg_types = {
1861        "size": False,
1862        "units": False,
1863        "minimum": False,
1864        "maximum": False,
1865        "default": False,
1866    }
arg_types = {'size': False, 'units': False, 'minimum': False, 'maximum': False, 'default': False}
key = 'datablocksizeproperty'
class DefinerProperty(Property):
1869class DefinerProperty(Property):
1870    arg_types = {"this": True}
arg_types = {'this': True}
key = 'definerproperty'
class DistKeyProperty(Property):
1873class DistKeyProperty(Property):
1874    arg_types = {"this": True}
arg_types = {'this': True}
key = 'distkeyproperty'
class DistStyleProperty(Property):
1877class DistStyleProperty(Property):
1878    arg_types = {"this": True}
arg_types = {'this': True}
key = 'diststyleproperty'
class EngineProperty(Property):
1881class EngineProperty(Property):
1882    arg_types = {"this": True}
arg_types = {'this': True}
key = 'engineproperty'
class ToTableProperty(Property):
1885class ToTableProperty(Property):
1886    arg_types = {"this": True}
arg_types = {'this': True}
key = 'totableproperty'
class ExecuteAsProperty(Property):
1889class ExecuteAsProperty(Property):
1890    arg_types = {"this": True}
arg_types = {'this': True}
key = 'executeasproperty'
class ExternalProperty(Property):
1893class ExternalProperty(Property):
1894    arg_types = {"this": False}
arg_types = {'this': False}
key = 'externalproperty'
class FallbackProperty(Property):
1897class FallbackProperty(Property):
1898    arg_types = {"no": True, "protection": False}
arg_types = {'no': True, 'protection': False}
key = 'fallbackproperty'
class FileFormatProperty(Property):
1901class FileFormatProperty(Property):
1902    arg_types = {"this": True}
arg_types = {'this': True}
key = 'fileformatproperty'
class FreespaceProperty(Property):
1905class FreespaceProperty(Property):
1906    arg_types = {"this": True, "percent": False}
arg_types = {'this': True, 'percent': False}
key = 'freespaceproperty'
class InputOutputFormat(Expression):
1909class InputOutputFormat(Expression):
1910    arg_types = {"input_format": False, "output_format": False}
arg_types = {'input_format': False, 'output_format': False}
key = 'inputoutputformat'
class IsolatedLoadingProperty(Property):
1913class IsolatedLoadingProperty(Property):
1914    arg_types = {
1915        "no": True,
1916        "concurrent": True,
1917        "for_all": True,
1918        "for_insert": True,
1919        "for_none": True,
1920    }
arg_types = {'no': True, 'concurrent': True, 'for_all': True, 'for_insert': True, 'for_none': True}
key = 'isolatedloadingproperty'
class JournalProperty(Property):
1923class JournalProperty(Property):
1924    arg_types = {
1925        "no": False,
1926        "dual": False,
1927        "before": False,
1928        "local": False,
1929        "after": False,
1930    }
arg_types = {'no': False, 'dual': False, 'before': False, 'local': False, 'after': False}
key = 'journalproperty'
class LanguageProperty(Property):
1933class LanguageProperty(Property):
1934    arg_types = {"this": True}
arg_types = {'this': True}
key = 'languageproperty'
class DictProperty(Property):
1937class DictProperty(Property):
1938    arg_types = {"this": True, "kind": True, "settings": False}
arg_types = {'this': True, 'kind': True, 'settings': False}
key = 'dictproperty'
class DictSubProperty(Property):
1941class DictSubProperty(Property):
1942    pass
key = 'dictsubproperty'
class DictRange(Property):
1945class DictRange(Property):
1946    arg_types = {"this": True, "min": True, "max": True}
arg_types = {'this': True, 'min': True, 'max': True}
key = 'dictrange'
class OnCluster(Property):
1951class OnCluster(Property):
1952    arg_types = {"this": True}
arg_types = {'this': True}
key = 'oncluster'
class LikeProperty(Property):
1955class LikeProperty(Property):
1956    arg_types = {"this": True, "expressions": False}
arg_types = {'this': True, 'expressions': False}
key = 'likeproperty'
class LocationProperty(Property):
1959class LocationProperty(Property):
1960    arg_types = {"this": True}
arg_types = {'this': True}
key = 'locationproperty'
class LockingProperty(Property):
1963class LockingProperty(Property):
1964    arg_types = {
1965        "this": False,
1966        "kind": True,
1967        "for_or_in": True,
1968        "lock_type": True,
1969        "override": False,
1970    }
arg_types = {'this': False, 'kind': True, 'for_or_in': True, 'lock_type': True, 'override': False}
key = 'lockingproperty'
class LogProperty(Property):
1973class LogProperty(Property):
1974    arg_types = {"no": True}
arg_types = {'no': True}
key = 'logproperty'
class MaterializedProperty(Property):
1977class MaterializedProperty(Property):
1978    arg_types = {"this": False}
arg_types = {'this': False}
key = 'materializedproperty'
class MergeBlockRatioProperty(Property):
1981class MergeBlockRatioProperty(Property):
1982    arg_types = {"this": False, "no": False, "default": False, "percent": False}
arg_types = {'this': False, 'no': False, 'default': False, 'percent': False}
key = 'mergeblockratioproperty'
class NoPrimaryIndexProperty(Property):
1985class NoPrimaryIndexProperty(Property):
1986    arg_types = {}
arg_types = {}
key = 'noprimaryindexproperty'
class OnCommitProperty(Property):
1989class OnCommitProperty(Property):
1990    arg_type = {"delete": False}
arg_type = {'delete': False}
key = 'oncommitproperty'
class PartitionedByProperty(Property):
1993class PartitionedByProperty(Property):
1994    arg_types = {"this": True}
arg_types = {'this': True}
key = 'partitionedbyproperty'
class ReturnsProperty(Property):
1997class ReturnsProperty(Property):
1998    arg_types = {"this": True, "is_table": False, "table": False}
arg_types = {'this': True, 'is_table': False, 'table': False}
key = 'returnsproperty'
class RowFormatProperty(Property):
2001class RowFormatProperty(Property):
2002    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatproperty'
class RowFormatDelimitedProperty(Property):
2005class RowFormatDelimitedProperty(Property):
2006    # https://cwiki.apache.org/confluence/display/hive/languagemanual+dml
2007    arg_types = {
2008        "fields": False,
2009        "escaped": False,
2010        "collection_items": False,
2011        "map_keys": False,
2012        "lines": False,
2013        "null": False,
2014        "serde": False,
2015    }
arg_types = {'fields': False, 'escaped': False, 'collection_items': False, 'map_keys': False, 'lines': False, 'null': False, 'serde': False}
key = 'rowformatdelimitedproperty'
class RowFormatSerdeProperty(Property):
2018class RowFormatSerdeProperty(Property):
2019    arg_types = {"this": True}
arg_types = {'this': True}
key = 'rowformatserdeproperty'
class SchemaCommentProperty(Property):
2022class SchemaCommentProperty(Property):
2023    arg_types = {"this": True}
arg_types = {'this': True}
key = 'schemacommentproperty'
class SerdeProperties(Property):
2026class SerdeProperties(Property):
2027    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'serdeproperties'
class SetProperty(Property):
2030class SetProperty(Property):
2031    arg_types = {"multi": True}
arg_types = {'multi': True}
key = 'setproperty'
class SettingsProperty(Property):
2034class SettingsProperty(Property):
2035    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'settingsproperty'
class SortKeyProperty(Property):
2038class SortKeyProperty(Property):
2039    arg_types = {"this": True, "compound": False}
arg_types = {'this': True, 'compound': False}
key = 'sortkeyproperty'
class SqlSecurityProperty(Property):
2042class SqlSecurityProperty(Property):
2043    arg_types = {"definer": True}
arg_types = {'definer': True}
key = 'sqlsecurityproperty'
class StabilityProperty(Property):
2046class StabilityProperty(Property):
2047    arg_types = {"this": True}
arg_types = {'this': True}
key = 'stabilityproperty'
class TemporaryProperty(Property):
2050class TemporaryProperty(Property):
2051    arg_types = {}
arg_types = {}
key = 'temporaryproperty'
class TransientProperty(Property):
2054class TransientProperty(Property):
2055    arg_types = {"this": False}
arg_types = {'this': False}
key = 'transientproperty'
class VolatileProperty(Property):
2058class VolatileProperty(Property):
2059    arg_types = {"this": False}
arg_types = {'this': False}
key = 'volatileproperty'
class WithDataProperty(Property):
2062class WithDataProperty(Property):
2063    arg_types = {"no": True, "statistics": False}
arg_types = {'no': True, 'statistics': False}
key = 'withdataproperty'
class WithJournalTableProperty(Property):
2066class WithJournalTableProperty(Property):
2067    arg_types = {"this": True}
arg_types = {'this': True}
key = 'withjournaltableproperty'
class Properties(Expression):
2070class Properties(Expression):
2071    arg_types = {"expressions": True}
2072
2073    NAME_TO_PROPERTY = {
2074        "ALGORITHM": AlgorithmProperty,
2075        "AUTO_INCREMENT": AutoIncrementProperty,
2076        "CHARACTER SET": CharacterSetProperty,
2077        "COLLATE": CollateProperty,
2078        "COMMENT": SchemaCommentProperty,
2079        "DEFINER": DefinerProperty,
2080        "DISTKEY": DistKeyProperty,
2081        "DISTSTYLE": DistStyleProperty,
2082        "ENGINE": EngineProperty,
2083        "EXECUTE AS": ExecuteAsProperty,
2084        "FORMAT": FileFormatProperty,
2085        "LANGUAGE": LanguageProperty,
2086        "LOCATION": LocationProperty,
2087        "PARTITIONED_BY": PartitionedByProperty,
2088        "RETURNS": ReturnsProperty,
2089        "ROW_FORMAT": RowFormatProperty,
2090        "SORTKEY": SortKeyProperty,
2091    }
2092
2093    PROPERTY_TO_NAME = {v: k for k, v in NAME_TO_PROPERTY.items()}
2094
2095    # CREATE property locations
2096    # Form: schema specified
2097    #   create [POST_CREATE]
2098    #     table a [POST_NAME]
2099    #     (b int) [POST_SCHEMA]
2100    #     with ([POST_WITH])
2101    #     index (b) [POST_INDEX]
2102    #
2103    # Form: alias selection
2104    #   create [POST_CREATE]
2105    #     table a [POST_NAME]
2106    #     as [POST_ALIAS] (select * from b) [POST_EXPRESSION]
2107    #     index (c) [POST_INDEX]
2108    class Location(AutoName):
2109        POST_CREATE = auto()
2110        POST_NAME = auto()
2111        POST_SCHEMA = auto()
2112        POST_WITH = auto()
2113        POST_ALIAS = auto()
2114        POST_EXPRESSION = auto()
2115        POST_INDEX = auto()
2116        UNSUPPORTED = auto()
2117
2118    @classmethod
2119    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2120        expressions = []
2121        for key, value in properties_dict.items():
2122            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2123            if property_cls:
2124                expressions.append(property_cls(this=convert(value)))
2125            else:
2126                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2127
2128        return cls(expressions=expressions)
arg_types = {'expressions': True}
NAME_TO_PROPERTY = {'ALGORITHM': <class 'sqlglot.expressions.AlgorithmProperty'>, 'AUTO_INCREMENT': <class 'sqlglot.expressions.AutoIncrementProperty'>, 'CHARACTER SET': <class 'sqlglot.expressions.CharacterSetProperty'>, 'COLLATE': <class 'sqlglot.expressions.CollateProperty'>, 'COMMENT': <class 'sqlglot.expressions.SchemaCommentProperty'>, 'DEFINER': <class 'sqlglot.expressions.DefinerProperty'>, 'DISTKEY': <class 'sqlglot.expressions.DistKeyProperty'>, 'DISTSTYLE': <class 'sqlglot.expressions.DistStyleProperty'>, 'ENGINE': <class 'sqlglot.expressions.EngineProperty'>, 'EXECUTE AS': <class 'sqlglot.expressions.ExecuteAsProperty'>, 'FORMAT': <class 'sqlglot.expressions.FileFormatProperty'>, 'LANGUAGE': <class 'sqlglot.expressions.LanguageProperty'>, 'LOCATION': <class 'sqlglot.expressions.LocationProperty'>, 'PARTITIONED_BY': <class 'sqlglot.expressions.PartitionedByProperty'>, 'RETURNS': <class 'sqlglot.expressions.ReturnsProperty'>, 'ROW_FORMAT': <class 'sqlglot.expressions.RowFormatProperty'>, 'SORTKEY': <class 'sqlglot.expressions.SortKeyProperty'>}
PROPERTY_TO_NAME = {<class 'sqlglot.expressions.AlgorithmProperty'>: 'ALGORITHM', <class 'sqlglot.expressions.AutoIncrementProperty'>: 'AUTO_INCREMENT', <class 'sqlglot.expressions.CharacterSetProperty'>: 'CHARACTER SET', <class 'sqlglot.expressions.CollateProperty'>: 'COLLATE', <class 'sqlglot.expressions.SchemaCommentProperty'>: 'COMMENT', <class 'sqlglot.expressions.DefinerProperty'>: 'DEFINER', <class 'sqlglot.expressions.DistKeyProperty'>: 'DISTKEY', <class 'sqlglot.expressions.DistStyleProperty'>: 'DISTSTYLE', <class 'sqlglot.expressions.EngineProperty'>: 'ENGINE', <class 'sqlglot.expressions.ExecuteAsProperty'>: 'EXECUTE AS', <class 'sqlglot.expressions.FileFormatProperty'>: 'FORMAT', <class 'sqlglot.expressions.LanguageProperty'>: 'LANGUAGE', <class 'sqlglot.expressions.LocationProperty'>: 'LOCATION', <class 'sqlglot.expressions.PartitionedByProperty'>: 'PARTITIONED_BY', <class 'sqlglot.expressions.ReturnsProperty'>: 'RETURNS', <class 'sqlglot.expressions.RowFormatProperty'>: 'ROW_FORMAT', <class 'sqlglot.expressions.SortKeyProperty'>: 'SORTKEY'}
@classmethod
def from_dict(cls, properties_dict: Dict) -> sqlglot.expressions.Properties:
2118    @classmethod
2119    def from_dict(cls, properties_dict: t.Dict) -> Properties:
2120        expressions = []
2121        for key, value in properties_dict.items():
2122            property_cls = cls.NAME_TO_PROPERTY.get(key.upper())
2123            if property_cls:
2124                expressions.append(property_cls(this=convert(value)))
2125            else:
2126                expressions.append(Property(this=Literal.string(key), value=convert(value)))
2127
2128        return cls(expressions=expressions)
key = 'properties'
class Properties.Location(sqlglot.helper.AutoName):
2108    class Location(AutoName):
2109        POST_CREATE = auto()
2110        POST_NAME = auto()
2111        POST_SCHEMA = auto()
2112        POST_WITH = auto()
2113        POST_ALIAS = auto()
2114        POST_EXPRESSION = auto()
2115        POST_INDEX = auto()
2116        UNSUPPORTED = auto()

An enumeration.

POST_CREATE = <Location.POST_CREATE: 'POST_CREATE'>
POST_NAME = <Location.POST_NAME: 'POST_NAME'>
POST_SCHEMA = <Location.POST_SCHEMA: 'POST_SCHEMA'>
POST_WITH = <Location.POST_WITH: 'POST_WITH'>
POST_ALIAS = <Location.POST_ALIAS: 'POST_ALIAS'>
POST_EXPRESSION = <Location.POST_EXPRESSION: 'POST_EXPRESSION'>
POST_INDEX = <Location.POST_INDEX: 'POST_INDEX'>
UNSUPPORTED = <Location.UNSUPPORTED: 'UNSUPPORTED'>
Inherited Members
enum.Enum
name
value
class Qualify(Expression):
2131class Qualify(Expression):
2132    pass
key = 'qualify'
class Return(Expression):
2136class Return(Expression):
2137    pass
key = 'return'
class Reference(Expression):
2140class Reference(Expression):
2141    arg_types = {"this": True, "expressions": False, "options": False}
arg_types = {'this': True, 'expressions': False, 'options': False}
key = 'reference'
class Tuple(Expression):
2144class Tuple(Expression):
2145    arg_types = {"expressions": False}
2146
2147    def isin(
2148        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2149    ) -> In:
2150        return In(
2151            this=_maybe_copy(self, copy),
2152            expressions=[convert(e, copy=copy) for e in expressions],
2153            query=maybe_parse(query, copy=copy, **opts) if query else None,
2154        )
arg_types = {'expressions': False}
def isin( self, *expressions: Any, query: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.In:
2147    def isin(
2148        self, *expressions: t.Any, query: t.Optional[ExpOrStr] = None, copy: bool = True, **opts
2149    ) -> In:
2150        return In(
2151            this=_maybe_copy(self, copy),
2152            expressions=[convert(e, copy=copy) for e in expressions],
2153            query=maybe_parse(query, copy=copy, **opts) if query else None,
2154        )
key = 'tuple'
class Subqueryable(Unionable):
2157class Subqueryable(Unionable):
2158    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2159        """
2160        Convert this expression to an aliased expression that can be used as a Subquery.
2161
2162        Example:
2163            >>> subquery = Select().select("x").from_("tbl").subquery()
2164            >>> Select().select("x").from_(subquery).sql()
2165            'SELECT x FROM (SELECT x FROM tbl)'
2166
2167        Args:
2168            alias (str | Identifier): an optional alias for the subquery
2169            copy (bool): if `False`, modify this expression instance in-place.
2170
2171        Returns:
2172            Alias: the subquery
2173        """
2174        instance = _maybe_copy(self, copy)
2175        if not isinstance(alias, Expression):
2176            alias = TableAlias(this=to_identifier(alias)) if alias else None
2177
2178        return Subquery(this=instance, alias=alias)
2179
2180    def limit(
2181        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2182    ) -> Select:
2183        raise NotImplementedError
2184
2185    @property
2186    def ctes(self):
2187        with_ = self.args.get("with")
2188        if not with_:
2189            return []
2190        return with_.expressions
2191
2192    @property
2193    def selects(self):
2194        raise NotImplementedError("Subqueryable objects must implement `selects`")
2195
2196    @property
2197    def named_selects(self):
2198        raise NotImplementedError("Subqueryable objects must implement `named_selects`")
2199
2200    def with_(
2201        self,
2202        alias: ExpOrStr,
2203        as_: ExpOrStr,
2204        recursive: t.Optional[bool] = None,
2205        append: bool = True,
2206        dialect: DialectType = None,
2207        copy: bool = True,
2208        **opts,
2209    ) -> Subqueryable:
2210        """
2211        Append to or set the common table expressions.
2212
2213        Example:
2214            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2215            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2216
2217        Args:
2218            alias: the SQL code string to parse as the table name.
2219                If an `Expression` instance is passed, this is used as-is.
2220            as_: the SQL code string to parse as the table expression.
2221                If an `Expression` instance is passed, it will be used as-is.
2222            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2223            append: if `True`, add to any existing expressions.
2224                Otherwise, this resets the expressions.
2225            dialect: the dialect used to parse the input expression.
2226            copy: if `False`, modify this expression instance in-place.
2227            opts: other options to use to parse the input expressions.
2228
2229        Returns:
2230            The modified expression.
2231        """
2232        return _apply_cte_builder(
2233            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2234        )
def subquery( self, alias: Union[str, sqlglot.expressions.Expression, NoneType] = None, copy: bool = True) -> sqlglot.expressions.Subquery:
2158    def subquery(self, alias: t.Optional[ExpOrStr] = None, copy: bool = True) -> Subquery:
2159        """
2160        Convert this expression to an aliased expression that can be used as a Subquery.
2161
2162        Example:
2163            >>> subquery = Select().select("x").from_("tbl").subquery()
2164            >>> Select().select("x").from_(subquery).sql()
2165            'SELECT x FROM (SELECT x FROM tbl)'
2166
2167        Args:
2168            alias (str | Identifier): an optional alias for the subquery
2169            copy (bool): if `False`, modify this expression instance in-place.
2170
2171        Returns:
2172            Alias: the subquery
2173        """
2174        instance = _maybe_copy(self, copy)
2175        if not isinstance(alias, Expression):
2176            alias = TableAlias(this=to_identifier(alias)) if alias else None
2177
2178        return Subquery(this=instance, alias=alias)

Convert this expression to an aliased expression that can be used as a Subquery.

Example:
>>> subquery = Select().select("x").from_("tbl").subquery()
>>> Select().select("x").from_(subquery).sql()
'SELECT x FROM (SELECT x FROM tbl)'
Arguments:
  • alias (str | Identifier): an optional alias for the subquery
  • copy (bool): if False, modify this expression instance in-place.
Returns:

Alias: the subquery

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2180    def limit(
2181        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2182    ) -> Select:
2183        raise NotImplementedError
ctes
selects
named_selects
def with_( self, alias: Union[str, sqlglot.expressions.Expression], as_: Union[str, sqlglot.expressions.Expression], recursive: Optional[bool] = None, append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Subqueryable:
2200    def with_(
2201        self,
2202        alias: ExpOrStr,
2203        as_: ExpOrStr,
2204        recursive: t.Optional[bool] = None,
2205        append: bool = True,
2206        dialect: DialectType = None,
2207        copy: bool = True,
2208        **opts,
2209    ) -> Subqueryable:
2210        """
2211        Append to or set the common table expressions.
2212
2213        Example:
2214            >>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
2215            'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
2216
2217        Args:
2218            alias: the SQL code string to parse as the table name.
2219                If an `Expression` instance is passed, this is used as-is.
2220            as_: the SQL code string to parse as the table expression.
2221                If an `Expression` instance is passed, it will be used as-is.
2222            recursive: set the RECURSIVE part of the expression. Defaults to `False`.
2223            append: if `True`, add to any existing expressions.
2224                Otherwise, this resets the expressions.
2225            dialect: the dialect used to parse the input expression.
2226            copy: if `False`, modify this expression instance in-place.
2227            opts: other options to use to parse the input expressions.
2228
2229        Returns:
2230            The modified expression.
2231        """
2232        return _apply_cte_builder(
2233            self, alias, as_, recursive=recursive, append=append, dialect=dialect, copy=copy, **opts
2234        )

Append to or set the common table expressions.

Example:
>>> Select().with_("tbl2", as_="SELECT * FROM tbl").select("x").from_("tbl2").sql()
'WITH tbl2 AS (SELECT * FROM tbl) SELECT x FROM tbl2'
Arguments:
  • alias: the SQL code string to parse as the table name. If an Expression instance is passed, this is used as-is.
  • as_: the SQL code string to parse as the table expression. If an Expression instance is passed, it will be used as-is.
  • recursive: set the RECURSIVE part of the expression. Defaults to False.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified expression.

key = 'subqueryable'
QUERY_MODIFIERS = {'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
class WithTableHint(Expression):
2261class WithTableHint(Expression):
2262    arg_types = {"expressions": True}
arg_types = {'expressions': True}
key = 'withtablehint'
class IndexTableHint(Expression):
2266class IndexTableHint(Expression):
2267    arg_types = {"this": True, "expressions": False, "target": False}
arg_types = {'this': True, 'expressions': False, 'target': False}
key = 'indextablehint'
class Table(Expression):
2270class Table(Expression):
2271    arg_types = {
2272        "this": True,
2273        "alias": False,
2274        "db": False,
2275        "catalog": False,
2276        "laterals": False,
2277        "joins": False,
2278        "pivots": False,
2279        "hints": False,
2280        "system_time": False,
2281    }
2282
2283    @property
2284    def db(self) -> str:
2285        return self.text("db")
2286
2287    @property
2288    def catalog(self) -> str:
2289        return self.text("catalog")
2290
2291    @property
2292    def parts(self) -> t.List[Identifier]:
2293        """Return the parts of a table in order catalog, db, table."""
2294        return [
2295            t.cast(Identifier, self.args[part])
2296            for part in ("catalog", "db", "this")
2297            if self.args.get(part)
2298        ]
arg_types = {'this': True, 'alias': False, 'db': False, 'catalog': False, 'laterals': False, 'joins': False, 'pivots': False, 'hints': False, 'system_time': False}
db: str
catalog: str

Return the parts of a table in order catalog, db, table.

key = 'table'
class SystemTime(Expression):
2302class SystemTime(Expression):
2303    arg_types = {
2304        "this": False,
2305        "expression": False,
2306        "kind": True,
2307    }
arg_types = {'this': False, 'expression': False, 'kind': True}
key = 'systemtime'
class Union(Subqueryable):
2310class Union(Subqueryable):
2311    arg_types = {
2312        "with": False,
2313        "this": True,
2314        "expression": True,
2315        "distinct": False,
2316        **QUERY_MODIFIERS,
2317    }
2318
2319    def limit(
2320        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2321    ) -> Select:
2322        """
2323        Set the LIMIT expression.
2324
2325        Example:
2326            >>> select("1").union(select("1")).limit(1).sql()
2327            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2328
2329        Args:
2330            expression: the SQL code string to parse.
2331                This can also be an integer.
2332                If a `Limit` instance is passed, this is used as-is.
2333                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2334            dialect: the dialect used to parse the input expression.
2335            copy: if `False`, modify this expression instance in-place.
2336            opts: other options to use to parse the input expressions.
2337
2338        Returns:
2339            The limited subqueryable.
2340        """
2341        return (
2342            select("*")
2343            .from_(self.subquery(alias="_l_0", copy=copy))
2344            .limit(expression, dialect=dialect, copy=False, **opts)
2345        )
2346
2347    def select(
2348        self,
2349        *expressions: t.Optional[ExpOrStr],
2350        append: bool = True,
2351        dialect: DialectType = None,
2352        copy: bool = True,
2353        **opts,
2354    ) -> Union:
2355        """Append to or set the SELECT of the union recursively.
2356
2357        Example:
2358            >>> from sqlglot import parse_one
2359            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2360            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2361
2362        Args:
2363            *expressions: the SQL code strings to parse.
2364                If an `Expression` instance is passed, it will be used as-is.
2365            append: if `True`, add to any existing expressions.
2366                Otherwise, this resets the expressions.
2367            dialect: the dialect used to parse the input expressions.
2368            copy: if `False`, modify this expression instance in-place.
2369            opts: other options to use to parse the input expressions.
2370
2371        Returns:
2372            Union: the modified expression.
2373        """
2374        this = self.copy() if copy else self
2375        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2376        this.expression.unnest().select(
2377            *expressions, append=append, dialect=dialect, copy=False, **opts
2378        )
2379        return this
2380
2381    @property
2382    def named_selects(self):
2383        return self.this.unnest().named_selects
2384
2385    @property
2386    def is_star(self) -> bool:
2387        return self.this.is_star or self.expression.is_star
2388
2389    @property
2390    def selects(self):
2391        return self.this.unnest().selects
2392
2393    @property
2394    def left(self):
2395        return self.this
2396
2397    @property
2398    def right(self):
2399        return self.expression
arg_types = {'with': False, 'this': True, 'expression': True, 'distinct': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2319    def limit(
2320        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2321    ) -> Select:
2322        """
2323        Set the LIMIT expression.
2324
2325        Example:
2326            >>> select("1").union(select("1")).limit(1).sql()
2327            'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
2328
2329        Args:
2330            expression: the SQL code string to parse.
2331                This can also be an integer.
2332                If a `Limit` instance is passed, this is used as-is.
2333                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2334            dialect: the dialect used to parse the input expression.
2335            copy: if `False`, modify this expression instance in-place.
2336            opts: other options to use to parse the input expressions.
2337
2338        Returns:
2339            The limited subqueryable.
2340        """
2341        return (
2342            select("*")
2343            .from_(self.subquery(alias="_l_0", copy=copy))
2344            .limit(expression, dialect=dialect, copy=False, **opts)
2345        )

Set the LIMIT expression.

Example:
>>> select("1").union(select("1")).limit(1).sql()
'SELECT * FROM (SELECT 1 UNION SELECT 1) AS _l_0 LIMIT 1'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The limited subqueryable.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Union:
2347    def select(
2348        self,
2349        *expressions: t.Optional[ExpOrStr],
2350        append: bool = True,
2351        dialect: DialectType = None,
2352        copy: bool = True,
2353        **opts,
2354    ) -> Union:
2355        """Append to or set the SELECT of the union recursively.
2356
2357        Example:
2358            >>> from sqlglot import parse_one
2359            >>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
2360            'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
2361
2362        Args:
2363            *expressions: the SQL code strings to parse.
2364                If an `Expression` instance is passed, it will be used as-is.
2365            append: if `True`, add to any existing expressions.
2366                Otherwise, this resets the expressions.
2367            dialect: the dialect used to parse the input expressions.
2368            copy: if `False`, modify this expression instance in-place.
2369            opts: other options to use to parse the input expressions.
2370
2371        Returns:
2372            Union: the modified expression.
2373        """
2374        this = self.copy() if copy else self
2375        this.this.unnest().select(*expressions, append=append, dialect=dialect, copy=False, **opts)
2376        this.expression.unnest().select(
2377            *expressions, append=append, dialect=dialect, copy=False, **opts
2378        )
2379        return this

Append to or set the SELECT of the union recursively.

Example:
>>> from sqlglot import parse_one
>>> parse_one("select a from x union select a from y union select a from z").select("b").sql()
'SELECT a, b FROM x UNION SELECT a, b FROM y UNION SELECT a, b FROM z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Union: the modified expression.

named_selects
is_star: bool

Checks whether an expression is a star.

selects
left
right
key = 'union'
class Except(Union):
2402class Except(Union):
2403    pass
key = 'except'
class Intersect(Union):
2406class Intersect(Union):
2407    pass
key = 'intersect'
class Unnest(UDTF):
2410class Unnest(UDTF):
2411    arg_types = {
2412        "expressions": True,
2413        "ordinality": False,
2414        "alias": False,
2415        "offset": False,
2416    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False, 'offset': False}
key = 'unnest'
class Update(Expression):
2419class Update(Expression):
2420    arg_types = {
2421        "with": False,
2422        "this": False,
2423        "expressions": True,
2424        "from": False,
2425        "where": False,
2426        "returning": False,
2427        "limit": False,
2428    }
arg_types = {'with': False, 'this': False, 'expressions': True, 'from': False, 'where': False, 'returning': False, 'limit': False}
key = 'update'
class Values(UDTF):
2431class Values(UDTF):
2432    arg_types = {
2433        "expressions": True,
2434        "ordinality": False,
2435        "alias": False,
2436    }
arg_types = {'expressions': True, 'ordinality': False, 'alias': False}
key = 'values'
class Var(Expression):
2439class Var(Expression):
2440    pass
key = 'var'
class Schema(Expression):
2443class Schema(Expression):
2444    arg_types = {"this": False, "expressions": False}
arg_types = {'this': False, 'expressions': False}
key = 'schema'
class Lock(Expression):
2449class Lock(Expression):
2450    arg_types = {"update": True, "expressions": False, "wait": False}
arg_types = {'update': True, 'expressions': False, 'wait': False}
key = 'lock'
class Select(Subqueryable):
2453class Select(Subqueryable):
2454    arg_types = {
2455        "with": False,
2456        "kind": False,
2457        "expressions": False,
2458        "hint": False,
2459        "distinct": False,
2460        "into": False,
2461        "from": False,
2462        **QUERY_MODIFIERS,
2463    }
2464
2465    def from_(
2466        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2467    ) -> Select:
2468        """
2469        Set the FROM expression.
2470
2471        Example:
2472            >>> Select().from_("tbl").select("x").sql()
2473            'SELECT x FROM tbl'
2474
2475        Args:
2476            expression : the SQL code strings to parse.
2477                If a `From` instance is passed, this is used as-is.
2478                If another `Expression` instance is passed, it will be wrapped in a `From`.
2479            dialect: the dialect used to parse the input expression.
2480            copy: if `False`, modify this expression instance in-place.
2481            opts: other options to use to parse the input expressions.
2482
2483        Returns:
2484            The modified Select expression.
2485        """
2486        return _apply_builder(
2487            expression=expression,
2488            instance=self,
2489            arg="from",
2490            into=From,
2491            prefix="FROM",
2492            dialect=dialect,
2493            copy=copy,
2494            **opts,
2495        )
2496
2497    def group_by(
2498        self,
2499        *expressions: t.Optional[ExpOrStr],
2500        append: bool = True,
2501        dialect: DialectType = None,
2502        copy: bool = True,
2503        **opts,
2504    ) -> Select:
2505        """
2506        Set the GROUP BY expression.
2507
2508        Example:
2509            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2510            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2511
2512        Args:
2513            *expressions: the SQL code strings to parse.
2514                If a `Group` instance is passed, this is used as-is.
2515                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2516                If nothing is passed in then a group by is not applied to the expression
2517            append: if `True`, add to any existing expressions.
2518                Otherwise, this flattens all the `Group` expression into a single expression.
2519            dialect: the dialect used to parse the input expression.
2520            copy: if `False`, modify this expression instance in-place.
2521            opts: other options to use to parse the input expressions.
2522
2523        Returns:
2524            The modified Select expression.
2525        """
2526        if not expressions:
2527            return self if not copy else self.copy()
2528
2529        return _apply_child_list_builder(
2530            *expressions,
2531            instance=self,
2532            arg="group",
2533            append=append,
2534            copy=copy,
2535            prefix="GROUP BY",
2536            into=Group,
2537            dialect=dialect,
2538            **opts,
2539        )
2540
2541    def order_by(
2542        self,
2543        *expressions: t.Optional[ExpOrStr],
2544        append: bool = True,
2545        dialect: DialectType = None,
2546        copy: bool = True,
2547        **opts,
2548    ) -> Select:
2549        """
2550        Set the ORDER BY expression.
2551
2552        Example:
2553            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2554            'SELECT x FROM tbl ORDER BY x DESC'
2555
2556        Args:
2557            *expressions: the SQL code strings to parse.
2558                If a `Group` instance is passed, this is used as-is.
2559                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2560            append: if `True`, add to any existing expressions.
2561                Otherwise, this flattens all the `Order` expression into a single expression.
2562            dialect: the dialect used to parse the input expression.
2563            copy: if `False`, modify this expression instance in-place.
2564            opts: other options to use to parse the input expressions.
2565
2566        Returns:
2567            The modified Select expression.
2568        """
2569        return _apply_child_list_builder(
2570            *expressions,
2571            instance=self,
2572            arg="order",
2573            append=append,
2574            copy=copy,
2575            prefix="ORDER BY",
2576            into=Order,
2577            dialect=dialect,
2578            **opts,
2579        )
2580
2581    def sort_by(
2582        self,
2583        *expressions: t.Optional[ExpOrStr],
2584        append: bool = True,
2585        dialect: DialectType = None,
2586        copy: bool = True,
2587        **opts,
2588    ) -> Select:
2589        """
2590        Set the SORT BY expression.
2591
2592        Example:
2593            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2594            'SELECT x FROM tbl SORT BY x DESC'
2595
2596        Args:
2597            *expressions: the SQL code strings to parse.
2598                If a `Group` instance is passed, this is used as-is.
2599                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2600            append: if `True`, add to any existing expressions.
2601                Otherwise, this flattens all the `Order` expression into a single expression.
2602            dialect: the dialect used to parse the input expression.
2603            copy: if `False`, modify this expression instance in-place.
2604            opts: other options to use to parse the input expressions.
2605
2606        Returns:
2607            The modified Select expression.
2608        """
2609        return _apply_child_list_builder(
2610            *expressions,
2611            instance=self,
2612            arg="sort",
2613            append=append,
2614            copy=copy,
2615            prefix="SORT BY",
2616            into=Sort,
2617            dialect=dialect,
2618            **opts,
2619        )
2620
2621    def cluster_by(
2622        self,
2623        *expressions: t.Optional[ExpOrStr],
2624        append: bool = True,
2625        dialect: DialectType = None,
2626        copy: bool = True,
2627        **opts,
2628    ) -> Select:
2629        """
2630        Set the CLUSTER BY expression.
2631
2632        Example:
2633            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2634            'SELECT x FROM tbl CLUSTER BY x DESC'
2635
2636        Args:
2637            *expressions: the SQL code strings to parse.
2638                If a `Group` instance is passed, this is used as-is.
2639                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2640            append: if `True`, add to any existing expressions.
2641                Otherwise, this flattens all the `Order` expression into a single expression.
2642            dialect: the dialect used to parse the input expression.
2643            copy: if `False`, modify this expression instance in-place.
2644            opts: other options to use to parse the input expressions.
2645
2646        Returns:
2647            The modified Select expression.
2648        """
2649        return _apply_child_list_builder(
2650            *expressions,
2651            instance=self,
2652            arg="cluster",
2653            append=append,
2654            copy=copy,
2655            prefix="CLUSTER BY",
2656            into=Cluster,
2657            dialect=dialect,
2658            **opts,
2659        )
2660
2661    def limit(
2662        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2663    ) -> Select:
2664        """
2665        Set the LIMIT expression.
2666
2667        Example:
2668            >>> Select().from_("tbl").select("x").limit(10).sql()
2669            'SELECT x FROM tbl LIMIT 10'
2670
2671        Args:
2672            expression: the SQL code string to parse.
2673                This can also be an integer.
2674                If a `Limit` instance is passed, this is used as-is.
2675                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2676            dialect: the dialect used to parse the input expression.
2677            copy: if `False`, modify this expression instance in-place.
2678            opts: other options to use to parse the input expressions.
2679
2680        Returns:
2681            Select: the modified expression.
2682        """
2683        return _apply_builder(
2684            expression=expression,
2685            instance=self,
2686            arg="limit",
2687            into=Limit,
2688            prefix="LIMIT",
2689            dialect=dialect,
2690            copy=copy,
2691            **opts,
2692        )
2693
2694    def offset(
2695        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2696    ) -> Select:
2697        """
2698        Set the OFFSET expression.
2699
2700        Example:
2701            >>> Select().from_("tbl").select("x").offset(10).sql()
2702            'SELECT x FROM tbl OFFSET 10'
2703
2704        Args:
2705            expression: the SQL code string to parse.
2706                This can also be an integer.
2707                If a `Offset` instance is passed, this is used as-is.
2708                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2709            dialect: the dialect used to parse the input expression.
2710            copy: if `False`, modify this expression instance in-place.
2711            opts: other options to use to parse the input expressions.
2712
2713        Returns:
2714            The modified Select expression.
2715        """
2716        return _apply_builder(
2717            expression=expression,
2718            instance=self,
2719            arg="offset",
2720            into=Offset,
2721            prefix="OFFSET",
2722            dialect=dialect,
2723            copy=copy,
2724            **opts,
2725        )
2726
2727    def select(
2728        self,
2729        *expressions: t.Optional[ExpOrStr],
2730        append: bool = True,
2731        dialect: DialectType = None,
2732        copy: bool = True,
2733        **opts,
2734    ) -> Select:
2735        """
2736        Append to or set the SELECT expressions.
2737
2738        Example:
2739            >>> Select().select("x", "y").sql()
2740            'SELECT x, y'
2741
2742        Args:
2743            *expressions: the SQL code strings to parse.
2744                If an `Expression` instance is passed, it will be used as-is.
2745            append: if `True`, add to any existing expressions.
2746                Otherwise, this resets the expressions.
2747            dialect: the dialect used to parse the input expressions.
2748            copy: if `False`, modify this expression instance in-place.
2749            opts: other options to use to parse the input expressions.
2750
2751        Returns:
2752            The modified Select expression.
2753        """
2754        return _apply_list_builder(
2755            *expressions,
2756            instance=self,
2757            arg="expressions",
2758            append=append,
2759            dialect=dialect,
2760            copy=copy,
2761            **opts,
2762        )
2763
2764    def lateral(
2765        self,
2766        *expressions: t.Optional[ExpOrStr],
2767        append: bool = True,
2768        dialect: DialectType = None,
2769        copy: bool = True,
2770        **opts,
2771    ) -> Select:
2772        """
2773        Append to or set the LATERAL expressions.
2774
2775        Example:
2776            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2777            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2778
2779        Args:
2780            *expressions: the SQL code strings to parse.
2781                If an `Expression` instance is passed, it will be used as-is.
2782            append: if `True`, add to any existing expressions.
2783                Otherwise, this resets the expressions.
2784            dialect: the dialect used to parse the input expressions.
2785            copy: if `False`, modify this expression instance in-place.
2786            opts: other options to use to parse the input expressions.
2787
2788        Returns:
2789            The modified Select expression.
2790        """
2791        return _apply_list_builder(
2792            *expressions,
2793            instance=self,
2794            arg="laterals",
2795            append=append,
2796            into=Lateral,
2797            prefix="LATERAL VIEW",
2798            dialect=dialect,
2799            copy=copy,
2800            **opts,
2801        )
2802
2803    def join(
2804        self,
2805        expression: ExpOrStr,
2806        on: t.Optional[ExpOrStr] = None,
2807        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2808        append: bool = True,
2809        join_type: t.Optional[str] = None,
2810        join_alias: t.Optional[Identifier | str] = None,
2811        dialect: DialectType = None,
2812        copy: bool = True,
2813        **opts,
2814    ) -> Select:
2815        """
2816        Append to or set the JOIN expressions.
2817
2818        Example:
2819            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2820            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2821
2822            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2823            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2824
2825            Use `join_type` to change the type of join:
2826
2827            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2828            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2829
2830        Args:
2831            expression: the SQL code string to parse.
2832                If an `Expression` instance is passed, it will be used as-is.
2833            on: optionally specify the join "on" criteria as a SQL string.
2834                If an `Expression` instance is passed, it will be used as-is.
2835            using: optionally specify the join "using" criteria as a SQL string.
2836                If an `Expression` instance is passed, it will be used as-is.
2837            append: if `True`, add to any existing expressions.
2838                Otherwise, this resets the expressions.
2839            join_type: if set, alter the parsed join type.
2840            join_alias: an optional alias for the joined source.
2841            dialect: the dialect used to parse the input expressions.
2842            copy: if `False`, modify this expression instance in-place.
2843            opts: other options to use to parse the input expressions.
2844
2845        Returns:
2846            Select: the modified expression.
2847        """
2848        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2849
2850        try:
2851            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2852        except ParseError:
2853            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2854
2855        join = expression if isinstance(expression, Join) else Join(this=expression)
2856
2857        if isinstance(join.this, Select):
2858            join.this.replace(join.this.subquery())
2859
2860        if join_type:
2861            method: t.Optional[Token]
2862            side: t.Optional[Token]
2863            kind: t.Optional[Token]
2864
2865            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2866
2867            if method:
2868                join.set("method", method.text)
2869            if side:
2870                join.set("side", side.text)
2871            if kind:
2872                join.set("kind", kind.text)
2873
2874        if on:
2875            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2876            join.set("on", on)
2877
2878        if using:
2879            join = _apply_list_builder(
2880                *ensure_list(using),
2881                instance=join,
2882                arg="using",
2883                append=append,
2884                copy=copy,
2885                **opts,
2886            )
2887
2888        if join_alias:
2889            join.set("this", alias_(join.this, join_alias, table=True))
2890
2891        return _apply_list_builder(
2892            join,
2893            instance=self,
2894            arg="joins",
2895            append=append,
2896            copy=copy,
2897            **opts,
2898        )
2899
2900    def where(
2901        self,
2902        *expressions: t.Optional[ExpOrStr],
2903        append: bool = True,
2904        dialect: DialectType = None,
2905        copy: bool = True,
2906        **opts,
2907    ) -> Select:
2908        """
2909        Append to or set the WHERE expressions.
2910
2911        Example:
2912            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2913            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2914
2915        Args:
2916            *expressions: the SQL code strings to parse.
2917                If an `Expression` instance is passed, it will be used as-is.
2918                Multiple expressions are combined with an AND operator.
2919            append: if `True`, AND the new expressions to any existing expression.
2920                Otherwise, this resets the expression.
2921            dialect: the dialect used to parse the input expressions.
2922            copy: if `False`, modify this expression instance in-place.
2923            opts: other options to use to parse the input expressions.
2924
2925        Returns:
2926            Select: the modified expression.
2927        """
2928        return _apply_conjunction_builder(
2929            *expressions,
2930            instance=self,
2931            arg="where",
2932            append=append,
2933            into=Where,
2934            dialect=dialect,
2935            copy=copy,
2936            **opts,
2937        )
2938
2939    def having(
2940        self,
2941        *expressions: t.Optional[ExpOrStr],
2942        append: bool = True,
2943        dialect: DialectType = None,
2944        copy: bool = True,
2945        **opts,
2946    ) -> Select:
2947        """
2948        Append to or set the HAVING expressions.
2949
2950        Example:
2951            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2952            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2953
2954        Args:
2955            *expressions: the SQL code strings to parse.
2956                If an `Expression` instance is passed, it will be used as-is.
2957                Multiple expressions are combined with an AND operator.
2958            append: if `True`, AND the new expressions to any existing expression.
2959                Otherwise, this resets the expression.
2960            dialect: the dialect used to parse the input expressions.
2961            copy: if `False`, modify this expression instance in-place.
2962            opts: other options to use to parse the input expressions.
2963
2964        Returns:
2965            The modified Select expression.
2966        """
2967        return _apply_conjunction_builder(
2968            *expressions,
2969            instance=self,
2970            arg="having",
2971            append=append,
2972            into=Having,
2973            dialect=dialect,
2974            copy=copy,
2975            **opts,
2976        )
2977
2978    def window(
2979        self,
2980        *expressions: t.Optional[ExpOrStr],
2981        append: bool = True,
2982        dialect: DialectType = None,
2983        copy: bool = True,
2984        **opts,
2985    ) -> Select:
2986        return _apply_list_builder(
2987            *expressions,
2988            instance=self,
2989            arg="windows",
2990            append=append,
2991            into=Window,
2992            dialect=dialect,
2993            copy=copy,
2994            **opts,
2995        )
2996
2997    def qualify(
2998        self,
2999        *expressions: t.Optional[ExpOrStr],
3000        append: bool = True,
3001        dialect: DialectType = None,
3002        copy: bool = True,
3003        **opts,
3004    ) -> Select:
3005        return _apply_conjunction_builder(
3006            *expressions,
3007            instance=self,
3008            arg="qualify",
3009            append=append,
3010            into=Qualify,
3011            dialect=dialect,
3012            copy=copy,
3013            **opts,
3014        )
3015
3016    def distinct(
3017        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3018    ) -> Select:
3019        """
3020        Set the OFFSET expression.
3021
3022        Example:
3023            >>> Select().from_("tbl").select("x").distinct().sql()
3024            'SELECT DISTINCT x FROM tbl'
3025
3026        Args:
3027            ons: the expressions to distinct on
3028            distinct: whether the Select should be distinct
3029            copy: if `False`, modify this expression instance in-place.
3030
3031        Returns:
3032            Select: the modified expression.
3033        """
3034        instance = _maybe_copy(self, copy)
3035        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3036        instance.set("distinct", Distinct(on=on) if distinct else None)
3037        return instance
3038
3039    def ctas(
3040        self,
3041        table: ExpOrStr,
3042        properties: t.Optional[t.Dict] = None,
3043        dialect: DialectType = None,
3044        copy: bool = True,
3045        **opts,
3046    ) -> Create:
3047        """
3048        Convert this expression to a CREATE TABLE AS statement.
3049
3050        Example:
3051            >>> Select().select("*").from_("tbl").ctas("x").sql()
3052            'CREATE TABLE x AS SELECT * FROM tbl'
3053
3054        Args:
3055            table: the SQL code string to parse as the table name.
3056                If another `Expression` instance is passed, it will be used as-is.
3057            properties: an optional mapping of table properties
3058            dialect: the dialect used to parse the input table.
3059            copy: if `False`, modify this expression instance in-place.
3060            opts: other options to use to parse the input table.
3061
3062        Returns:
3063            The new Create expression.
3064        """
3065        instance = _maybe_copy(self, copy)
3066        table_expression = maybe_parse(
3067            table,
3068            into=Table,
3069            dialect=dialect,
3070            **opts,
3071        )
3072        properties_expression = None
3073        if properties:
3074            properties_expression = Properties.from_dict(properties)
3075
3076        return Create(
3077            this=table_expression,
3078            kind="table",
3079            expression=instance,
3080            properties=properties_expression,
3081        )
3082
3083    def lock(self, update: bool = True, copy: bool = True) -> Select:
3084        """
3085        Set the locking read mode for this expression.
3086
3087        Examples:
3088            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3089            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3090
3091            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3092            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3093
3094        Args:
3095            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3096            copy: if `False`, modify this expression instance in-place.
3097
3098        Returns:
3099            The modified expression.
3100        """
3101        inst = _maybe_copy(self, copy)
3102        inst.set("locks", [Lock(update=update)])
3103
3104        return inst
3105
3106    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3107        """
3108        Set hints for this expression.
3109
3110        Examples:
3111            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3112            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3113
3114        Args:
3115            hints: The SQL code strings to parse as the hints.
3116                If an `Expression` instance is passed, it will be used as-is.
3117            dialect: The dialect used to parse the hints.
3118            copy: If `False`, modify this expression instance in-place.
3119
3120        Returns:
3121            The modified expression.
3122        """
3123        inst = _maybe_copy(self, copy)
3124        inst.set(
3125            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3126        )
3127
3128        return inst
3129
3130    @property
3131    def named_selects(self) -> t.List[str]:
3132        return [e.output_name for e in self.expressions if e.alias_or_name]
3133
3134    @property
3135    def is_star(self) -> bool:
3136        return any(expression.is_star for expression in self.expressions)
3137
3138    @property
3139    def selects(self) -> t.List[Expression]:
3140        return self.expressions
arg_types = {'with': False, 'kind': False, 'expressions': False, 'hint': False, 'distinct': False, 'into': False, 'from': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def from_( self, expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2465    def from_(
2466        self, expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
2467    ) -> Select:
2468        """
2469        Set the FROM expression.
2470
2471        Example:
2472            >>> Select().from_("tbl").select("x").sql()
2473            'SELECT x FROM tbl'
2474
2475        Args:
2476            expression : the SQL code strings to parse.
2477                If a `From` instance is passed, this is used as-is.
2478                If another `Expression` instance is passed, it will be wrapped in a `From`.
2479            dialect: the dialect used to parse the input expression.
2480            copy: if `False`, modify this expression instance in-place.
2481            opts: other options to use to parse the input expressions.
2482
2483        Returns:
2484            The modified Select expression.
2485        """
2486        return _apply_builder(
2487            expression=expression,
2488            instance=self,
2489            arg="from",
2490            into=From,
2491            prefix="FROM",
2492            dialect=dialect,
2493            copy=copy,
2494            **opts,
2495        )

Set the FROM expression.

Example:
>>> Select().from_("tbl").select("x").sql()
'SELECT x FROM tbl'
Arguments:
  • expression : the SQL code strings to parse. If a From instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a From.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def group_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2497    def group_by(
2498        self,
2499        *expressions: t.Optional[ExpOrStr],
2500        append: bool = True,
2501        dialect: DialectType = None,
2502        copy: bool = True,
2503        **opts,
2504    ) -> Select:
2505        """
2506        Set the GROUP BY expression.
2507
2508        Example:
2509            >>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
2510            'SELECT x, COUNT(1) FROM tbl GROUP BY x'
2511
2512        Args:
2513            *expressions: the SQL code strings to parse.
2514                If a `Group` instance is passed, this is used as-is.
2515                If another `Expression` instance is passed, it will be wrapped in a `Group`.
2516                If nothing is passed in then a group by is not applied to the expression
2517            append: if `True`, add to any existing expressions.
2518                Otherwise, this flattens all the `Group` expression into a single expression.
2519            dialect: the dialect used to parse the input expression.
2520            copy: if `False`, modify this expression instance in-place.
2521            opts: other options to use to parse the input expressions.
2522
2523        Returns:
2524            The modified Select expression.
2525        """
2526        if not expressions:
2527            return self if not copy else self.copy()
2528
2529        return _apply_child_list_builder(
2530            *expressions,
2531            instance=self,
2532            arg="group",
2533            append=append,
2534            copy=copy,
2535            prefix="GROUP BY",
2536            into=Group,
2537            dialect=dialect,
2538            **opts,
2539        )

Set the GROUP BY expression.

Example:
>>> Select().from_("tbl").select("x", "COUNT(1)").group_by("x").sql()
'SELECT x, COUNT(1) FROM tbl GROUP BY x'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Group. If nothing is passed in then a group by is not applied to the expression
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Group expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def order_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2541    def order_by(
2542        self,
2543        *expressions: t.Optional[ExpOrStr],
2544        append: bool = True,
2545        dialect: DialectType = None,
2546        copy: bool = True,
2547        **opts,
2548    ) -> Select:
2549        """
2550        Set the ORDER BY expression.
2551
2552        Example:
2553            >>> Select().from_("tbl").select("x").order_by("x DESC").sql()
2554            'SELECT x FROM tbl ORDER BY x DESC'
2555
2556        Args:
2557            *expressions: the SQL code strings to parse.
2558                If a `Group` instance is passed, this is used as-is.
2559                If another `Expression` instance is passed, it will be wrapped in a `Order`.
2560            append: if `True`, add to any existing expressions.
2561                Otherwise, this flattens all the `Order` expression into a single expression.
2562            dialect: the dialect used to parse the input expression.
2563            copy: if `False`, modify this expression instance in-place.
2564            opts: other options to use to parse the input expressions.
2565
2566        Returns:
2567            The modified Select expression.
2568        """
2569        return _apply_child_list_builder(
2570            *expressions,
2571            instance=self,
2572            arg="order",
2573            append=append,
2574            copy=copy,
2575            prefix="ORDER BY",
2576            into=Order,
2577            dialect=dialect,
2578            **opts,
2579        )

Set the ORDER BY expression.

Example:
>>> Select().from_("tbl").select("x").order_by("x DESC").sql()
'SELECT x FROM tbl ORDER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Order.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def sort_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2581    def sort_by(
2582        self,
2583        *expressions: t.Optional[ExpOrStr],
2584        append: bool = True,
2585        dialect: DialectType = None,
2586        copy: bool = True,
2587        **opts,
2588    ) -> Select:
2589        """
2590        Set the SORT BY expression.
2591
2592        Example:
2593            >>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
2594            'SELECT x FROM tbl SORT BY x DESC'
2595
2596        Args:
2597            *expressions: the SQL code strings to parse.
2598                If a `Group` instance is passed, this is used as-is.
2599                If another `Expression` instance is passed, it will be wrapped in a `SORT`.
2600            append: if `True`, add to any existing expressions.
2601                Otherwise, this flattens all the `Order` expression into a single expression.
2602            dialect: the dialect used to parse the input expression.
2603            copy: if `False`, modify this expression instance in-place.
2604            opts: other options to use to parse the input expressions.
2605
2606        Returns:
2607            The modified Select expression.
2608        """
2609        return _apply_child_list_builder(
2610            *expressions,
2611            instance=self,
2612            arg="sort",
2613            append=append,
2614            copy=copy,
2615            prefix="SORT BY",
2616            into=Sort,
2617            dialect=dialect,
2618            **opts,
2619        )

Set the SORT BY expression.

Example:
>>> Select().from_("tbl").select("x").sort_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl SORT BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a SORT.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def cluster_by( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2621    def cluster_by(
2622        self,
2623        *expressions: t.Optional[ExpOrStr],
2624        append: bool = True,
2625        dialect: DialectType = None,
2626        copy: bool = True,
2627        **opts,
2628    ) -> Select:
2629        """
2630        Set the CLUSTER BY expression.
2631
2632        Example:
2633            >>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
2634            'SELECT x FROM tbl CLUSTER BY x DESC'
2635
2636        Args:
2637            *expressions: the SQL code strings to parse.
2638                If a `Group` instance is passed, this is used as-is.
2639                If another `Expression` instance is passed, it will be wrapped in a `Cluster`.
2640            append: if `True`, add to any existing expressions.
2641                Otherwise, this flattens all the `Order` expression into a single expression.
2642            dialect: the dialect used to parse the input expression.
2643            copy: if `False`, modify this expression instance in-place.
2644            opts: other options to use to parse the input expressions.
2645
2646        Returns:
2647            The modified Select expression.
2648        """
2649        return _apply_child_list_builder(
2650            *expressions,
2651            instance=self,
2652            arg="cluster",
2653            append=append,
2654            copy=copy,
2655            prefix="CLUSTER BY",
2656            into=Cluster,
2657            dialect=dialect,
2658            **opts,
2659        )

Set the CLUSTER BY expression.

Example:
>>> Select().from_("tbl").select("x").cluster_by("x DESC").sql(dialect="hive")
'SELECT x FROM tbl CLUSTER BY x DESC'
Arguments:
  • *expressions: the SQL code strings to parse. If a Group instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Cluster.
  • append: if True, add to any existing expressions. Otherwise, this flattens all the Order expression into a single expression.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def limit( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2661    def limit(
2662        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2663    ) -> Select:
2664        """
2665        Set the LIMIT expression.
2666
2667        Example:
2668            >>> Select().from_("tbl").select("x").limit(10).sql()
2669            'SELECT x FROM tbl LIMIT 10'
2670
2671        Args:
2672            expression: the SQL code string to parse.
2673                This can also be an integer.
2674                If a `Limit` instance is passed, this is used as-is.
2675                If another `Expression` instance is passed, it will be wrapped in a `Limit`.
2676            dialect: the dialect used to parse the input expression.
2677            copy: if `False`, modify this expression instance in-place.
2678            opts: other options to use to parse the input expressions.
2679
2680        Returns:
2681            Select: the modified expression.
2682        """
2683        return _apply_builder(
2684            expression=expression,
2685            instance=self,
2686            arg="limit",
2687            into=Limit,
2688            prefix="LIMIT",
2689            dialect=dialect,
2690            copy=copy,
2691            **opts,
2692        )

Set the LIMIT expression.

Example:
>>> Select().from_("tbl").select("x").limit(10).sql()
'SELECT x FROM tbl LIMIT 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Limit instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Limit.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def offset( self, expression: Union[str, sqlglot.expressions.Expression, int], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2694    def offset(
2695        self, expression: ExpOrStr | int, dialect: DialectType = None, copy: bool = True, **opts
2696    ) -> Select:
2697        """
2698        Set the OFFSET expression.
2699
2700        Example:
2701            >>> Select().from_("tbl").select("x").offset(10).sql()
2702            'SELECT x FROM tbl OFFSET 10'
2703
2704        Args:
2705            expression: the SQL code string to parse.
2706                This can also be an integer.
2707                If a `Offset` instance is passed, this is used as-is.
2708                If another `Expression` instance is passed, it will be wrapped in a `Offset`.
2709            dialect: the dialect used to parse the input expression.
2710            copy: if `False`, modify this expression instance in-place.
2711            opts: other options to use to parse the input expressions.
2712
2713        Returns:
2714            The modified Select expression.
2715        """
2716        return _apply_builder(
2717            expression=expression,
2718            instance=self,
2719            arg="offset",
2720            into=Offset,
2721            prefix="OFFSET",
2722            dialect=dialect,
2723            copy=copy,
2724            **opts,
2725        )

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").offset(10).sql()
'SELECT x FROM tbl OFFSET 10'
Arguments:
  • expression: the SQL code string to parse. This can also be an integer. If a Offset instance is passed, this is used as-is. If another Expression instance is passed, it will be wrapped in a Offset.
  • dialect: the dialect used to parse the input expression.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def select( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2727    def select(
2728        self,
2729        *expressions: t.Optional[ExpOrStr],
2730        append: bool = True,
2731        dialect: DialectType = None,
2732        copy: bool = True,
2733        **opts,
2734    ) -> Select:
2735        """
2736        Append to or set the SELECT expressions.
2737
2738        Example:
2739            >>> Select().select("x", "y").sql()
2740            'SELECT x, y'
2741
2742        Args:
2743            *expressions: the SQL code strings to parse.
2744                If an `Expression` instance is passed, it will be used as-is.
2745            append: if `True`, add to any existing expressions.
2746                Otherwise, this resets the expressions.
2747            dialect: the dialect used to parse the input expressions.
2748            copy: if `False`, modify this expression instance in-place.
2749            opts: other options to use to parse the input expressions.
2750
2751        Returns:
2752            The modified Select expression.
2753        """
2754        return _apply_list_builder(
2755            *expressions,
2756            instance=self,
2757            arg="expressions",
2758            append=append,
2759            dialect=dialect,
2760            copy=copy,
2761            **opts,
2762        )

Append to or set the SELECT expressions.

Example:
>>> Select().select("x", "y").sql()
'SELECT x, y'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def lateral( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2764    def lateral(
2765        self,
2766        *expressions: t.Optional[ExpOrStr],
2767        append: bool = True,
2768        dialect: DialectType = None,
2769        copy: bool = True,
2770        **opts,
2771    ) -> Select:
2772        """
2773        Append to or set the LATERAL expressions.
2774
2775        Example:
2776            >>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
2777            'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
2778
2779        Args:
2780            *expressions: the SQL code strings to parse.
2781                If an `Expression` instance is passed, it will be used as-is.
2782            append: if `True`, add to any existing expressions.
2783                Otherwise, this resets the expressions.
2784            dialect: the dialect used to parse the input expressions.
2785            copy: if `False`, modify this expression instance in-place.
2786            opts: other options to use to parse the input expressions.
2787
2788        Returns:
2789            The modified Select expression.
2790        """
2791        return _apply_list_builder(
2792            *expressions,
2793            instance=self,
2794            arg="laterals",
2795            append=append,
2796            into=Lateral,
2797            prefix="LATERAL VIEW",
2798            dialect=dialect,
2799            copy=copy,
2800            **opts,
2801        )

Append to or set the LATERAL expressions.

Example:
>>> Select().select("x").lateral("OUTER explode(y) tbl2 AS z").from_("tbl").sql()
'SELECT x FROM tbl LATERAL VIEW OUTER EXPLODE(y) tbl2 AS z'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def join( self, expression: Union[str, sqlglot.expressions.Expression], on: Union[str, sqlglot.expressions.Expression, NoneType] = None, using: Union[str, sqlglot.expressions.Expression, List[Union[str, sqlglot.expressions.Expression]], NoneType] = None, append: bool = True, join_type: Optional[str] = None, join_alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2803    def join(
2804        self,
2805        expression: ExpOrStr,
2806        on: t.Optional[ExpOrStr] = None,
2807        using: t.Optional[ExpOrStr | t.List[ExpOrStr]] = None,
2808        append: bool = True,
2809        join_type: t.Optional[str] = None,
2810        join_alias: t.Optional[Identifier | str] = None,
2811        dialect: DialectType = None,
2812        copy: bool = True,
2813        **opts,
2814    ) -> Select:
2815        """
2816        Append to or set the JOIN expressions.
2817
2818        Example:
2819            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
2820            'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
2821
2822            >>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
2823            'SELECT 1 FROM a JOIN b USING (x, y, z)'
2824
2825            Use `join_type` to change the type of join:
2826
2827            >>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
2828            'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
2829
2830        Args:
2831            expression: the SQL code string to parse.
2832                If an `Expression` instance is passed, it will be used as-is.
2833            on: optionally specify the join "on" criteria as a SQL string.
2834                If an `Expression` instance is passed, it will be used as-is.
2835            using: optionally specify the join "using" criteria as a SQL string.
2836                If an `Expression` instance is passed, it will be used as-is.
2837            append: if `True`, add to any existing expressions.
2838                Otherwise, this resets the expressions.
2839            join_type: if set, alter the parsed join type.
2840            join_alias: an optional alias for the joined source.
2841            dialect: the dialect used to parse the input expressions.
2842            copy: if `False`, modify this expression instance in-place.
2843            opts: other options to use to parse the input expressions.
2844
2845        Returns:
2846            Select: the modified expression.
2847        """
2848        parse_args: t.Dict[str, t.Any] = {"dialect": dialect, **opts}
2849
2850        try:
2851            expression = maybe_parse(expression, into=Join, prefix="JOIN", **parse_args)
2852        except ParseError:
2853            expression = maybe_parse(expression, into=(Join, Expression), **parse_args)
2854
2855        join = expression if isinstance(expression, Join) else Join(this=expression)
2856
2857        if isinstance(join.this, Select):
2858            join.this.replace(join.this.subquery())
2859
2860        if join_type:
2861            method: t.Optional[Token]
2862            side: t.Optional[Token]
2863            kind: t.Optional[Token]
2864
2865            method, side, kind = maybe_parse(join_type, into="JOIN_TYPE", **parse_args)  # type: ignore
2866
2867            if method:
2868                join.set("method", method.text)
2869            if side:
2870                join.set("side", side.text)
2871            if kind:
2872                join.set("kind", kind.text)
2873
2874        if on:
2875            on = and_(*ensure_list(on), dialect=dialect, copy=copy, **opts)
2876            join.set("on", on)
2877
2878        if using:
2879            join = _apply_list_builder(
2880                *ensure_list(using),
2881                instance=join,
2882                arg="using",
2883                append=append,
2884                copy=copy,
2885                **opts,
2886            )
2887
2888        if join_alias:
2889            join.set("this", alias_(join.this, join_alias, table=True))
2890
2891        return _apply_list_builder(
2892            join,
2893            instance=self,
2894            arg="joins",
2895            append=append,
2896            copy=copy,
2897            **opts,
2898        )

Append to or set the JOIN expressions.

Example:
>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y").sql()
'SELECT * FROM tbl JOIN tbl2 ON tbl1.y = tbl2.y'
>>> Select().select("1").from_("a").join("b", using=["x", "y", "z"]).sql()
'SELECT 1 FROM a JOIN b USING (x, y, z)'

Use join_type to change the type of join:

>>> Select().select("*").from_("tbl").join("tbl2", on="tbl1.y = tbl2.y", join_type="left outer").sql()
'SELECT * FROM tbl LEFT OUTER JOIN tbl2 ON tbl1.y = tbl2.y'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, it will be used as-is.
  • on: optionally specify the join "on" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • using: optionally specify the join "using" criteria as a SQL string. If an Expression instance is passed, it will be used as-is.
  • append: if True, add to any existing expressions. Otherwise, this resets the expressions.
  • join_type: if set, alter the parsed join type.
  • join_alias: an optional alias for the joined source.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def where( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2900    def where(
2901        self,
2902        *expressions: t.Optional[ExpOrStr],
2903        append: bool = True,
2904        dialect: DialectType = None,
2905        copy: bool = True,
2906        **opts,
2907    ) -> Select:
2908        """
2909        Append to or set the WHERE expressions.
2910
2911        Example:
2912            >>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
2913            "SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
2914
2915        Args:
2916            *expressions: the SQL code strings to parse.
2917                If an `Expression` instance is passed, it will be used as-is.
2918                Multiple expressions are combined with an AND operator.
2919            append: if `True`, AND the new expressions to any existing expression.
2920                Otherwise, this resets the expression.
2921            dialect: the dialect used to parse the input expressions.
2922            copy: if `False`, modify this expression instance in-place.
2923            opts: other options to use to parse the input expressions.
2924
2925        Returns:
2926            Select: the modified expression.
2927        """
2928        return _apply_conjunction_builder(
2929            *expressions,
2930            instance=self,
2931            arg="where",
2932            append=append,
2933            into=Where,
2934            dialect=dialect,
2935            copy=copy,
2936            **opts,
2937        )

Append to or set the WHERE expressions.

Example:
>>> Select().select("x").from_("tbl").where("x = 'a' OR x < 'b'").sql()
"SELECT x FROM tbl WHERE x = 'a' OR x < 'b'"
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

Select: the modified expression.

def having( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2939    def having(
2940        self,
2941        *expressions: t.Optional[ExpOrStr],
2942        append: bool = True,
2943        dialect: DialectType = None,
2944        copy: bool = True,
2945        **opts,
2946    ) -> Select:
2947        """
2948        Append to or set the HAVING expressions.
2949
2950        Example:
2951            >>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
2952            'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
2953
2954        Args:
2955            *expressions: the SQL code strings to parse.
2956                If an `Expression` instance is passed, it will be used as-is.
2957                Multiple expressions are combined with an AND operator.
2958            append: if `True`, AND the new expressions to any existing expression.
2959                Otherwise, this resets the expression.
2960            dialect: the dialect used to parse the input expressions.
2961            copy: if `False`, modify this expression instance in-place.
2962            opts: other options to use to parse the input expressions.
2963
2964        Returns:
2965            The modified Select expression.
2966        """
2967        return _apply_conjunction_builder(
2968            *expressions,
2969            instance=self,
2970            arg="having",
2971            append=append,
2972            into=Having,
2973            dialect=dialect,
2974            copy=copy,
2975            **opts,
2976        )

Append to or set the HAVING expressions.

Example:
>>> Select().select("x", "COUNT(y)").from_("tbl").group_by("x").having("COUNT(y) > 3").sql()
'SELECT x, COUNT(y) FROM tbl GROUP BY x HAVING COUNT(y) > 3'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, it will be used as-is. Multiple expressions are combined with an AND operator.
  • append: if True, AND the new expressions to any existing expression. Otherwise, this resets the expression.
  • dialect: the dialect used to parse the input expressions.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input expressions.
Returns:

The modified Select expression.

def window( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2978    def window(
2979        self,
2980        *expressions: t.Optional[ExpOrStr],
2981        append: bool = True,
2982        dialect: DialectType = None,
2983        copy: bool = True,
2984        **opts,
2985    ) -> Select:
2986        return _apply_list_builder(
2987            *expressions,
2988            instance=self,
2989            arg="windows",
2990            append=append,
2991            into=Window,
2992            dialect=dialect,
2993            copy=copy,
2994            **opts,
2995        )
def qualify( self, *expressions: Union[str, sqlglot.expressions.Expression, NoneType], append: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Select:
2997    def qualify(
2998        self,
2999        *expressions: t.Optional[ExpOrStr],
3000        append: bool = True,
3001        dialect: DialectType = None,
3002        copy: bool = True,
3003        **opts,
3004    ) -> Select:
3005        return _apply_conjunction_builder(
3006            *expressions,
3007            instance=self,
3008            arg="qualify",
3009            append=append,
3010            into=Qualify,
3011            dialect=dialect,
3012            copy=copy,
3013            **opts,
3014        )
def distinct( self, *ons: Union[str, sqlglot.expressions.Expression, NoneType], distinct: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3016    def distinct(
3017        self, *ons: t.Optional[ExpOrStr], distinct: bool = True, copy: bool = True
3018    ) -> Select:
3019        """
3020        Set the OFFSET expression.
3021
3022        Example:
3023            >>> Select().from_("tbl").select("x").distinct().sql()
3024            'SELECT DISTINCT x FROM tbl'
3025
3026        Args:
3027            ons: the expressions to distinct on
3028            distinct: whether the Select should be distinct
3029            copy: if `False`, modify this expression instance in-place.
3030
3031        Returns:
3032            Select: the modified expression.
3033        """
3034        instance = _maybe_copy(self, copy)
3035        on = Tuple(expressions=[maybe_parse(on, copy=copy) for on in ons if on]) if ons else None
3036        instance.set("distinct", Distinct(on=on) if distinct else None)
3037        return instance

Set the OFFSET expression.

Example:
>>> Select().from_("tbl").select("x").distinct().sql()
'SELECT DISTINCT x FROM tbl'
Arguments:
  • ons: the expressions to distinct on
  • distinct: whether the Select should be distinct
  • copy: if False, modify this expression instance in-place.
Returns:

Select: the modified expression.

def ctas( self, table: Union[str, sqlglot.expressions.Expression], properties: Optional[Dict] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Create:
3039    def ctas(
3040        self,
3041        table: ExpOrStr,
3042        properties: t.Optional[t.Dict] = None,
3043        dialect: DialectType = None,
3044        copy: bool = True,
3045        **opts,
3046    ) -> Create:
3047        """
3048        Convert this expression to a CREATE TABLE AS statement.
3049
3050        Example:
3051            >>> Select().select("*").from_("tbl").ctas("x").sql()
3052            'CREATE TABLE x AS SELECT * FROM tbl'
3053
3054        Args:
3055            table: the SQL code string to parse as the table name.
3056                If another `Expression` instance is passed, it will be used as-is.
3057            properties: an optional mapping of table properties
3058            dialect: the dialect used to parse the input table.
3059            copy: if `False`, modify this expression instance in-place.
3060            opts: other options to use to parse the input table.
3061
3062        Returns:
3063            The new Create expression.
3064        """
3065        instance = _maybe_copy(self, copy)
3066        table_expression = maybe_parse(
3067            table,
3068            into=Table,
3069            dialect=dialect,
3070            **opts,
3071        )
3072        properties_expression = None
3073        if properties:
3074            properties_expression = Properties.from_dict(properties)
3075
3076        return Create(
3077            this=table_expression,
3078            kind="table",
3079            expression=instance,
3080            properties=properties_expression,
3081        )

Convert this expression to a CREATE TABLE AS statement.

Example:
>>> Select().select("*").from_("tbl").ctas("x").sql()
'CREATE TABLE x AS SELECT * FROM tbl'
Arguments:
  • table: the SQL code string to parse as the table name. If another Expression instance is passed, it will be used as-is.
  • properties: an optional mapping of table properties
  • dialect: the dialect used to parse the input table.
  • copy: if False, modify this expression instance in-place.
  • opts: other options to use to parse the input table.
Returns:

The new Create expression.

def lock( self, update: bool = True, copy: bool = True) -> sqlglot.expressions.Select:
3083    def lock(self, update: bool = True, copy: bool = True) -> Select:
3084        """
3085        Set the locking read mode for this expression.
3086
3087        Examples:
3088            >>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
3089            "SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
3090
3091            >>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
3092            "SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
3093
3094        Args:
3095            update: if `True`, the locking type will be `FOR UPDATE`, else it will be `FOR SHARE`.
3096            copy: if `False`, modify this expression instance in-place.
3097
3098        Returns:
3099            The modified expression.
3100        """
3101        inst = _maybe_copy(self, copy)
3102        inst.set("locks", [Lock(update=update)])
3103
3104        return inst

Set the locking read mode for this expression.

Examples:
>>> Select().select("x").from_("tbl").where("x = 'a'").lock().sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR UPDATE"
>>> Select().select("x").from_("tbl").where("x = 'a'").lock(update=False).sql("mysql")
"SELECT x FROM tbl WHERE x = 'a' FOR SHARE"
Arguments:
  • update: if True, the locking type will be FOR UPDATE, else it will be FOR SHARE.
  • copy: if False, modify this expression instance in-place.
Returns:

The modified expression.

def hint( self, *hints: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True) -> sqlglot.expressions.Select:
3106    def hint(self, *hints: ExpOrStr, dialect: DialectType = None, copy: bool = True) -> Select:
3107        """
3108        Set hints for this expression.
3109
3110        Examples:
3111            >>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
3112            'SELECT /*+ BROADCAST(y) */ x FROM tbl'
3113
3114        Args:
3115            hints: The SQL code strings to parse as the hints.
3116                If an `Expression` instance is passed, it will be used as-is.
3117            dialect: The dialect used to parse the hints.
3118            copy: If `False`, modify this expression instance in-place.
3119
3120        Returns:
3121            The modified expression.
3122        """
3123        inst = _maybe_copy(self, copy)
3124        inst.set(
3125            "hint", Hint(expressions=[maybe_parse(h, copy=copy, dialect=dialect) for h in hints])
3126        )
3127
3128        return inst

Set hints for this expression.

Examples:
>>> Select().select("x").from_("tbl").hint("BROADCAST(y)").sql(dialect="spark")
'SELECT /*+ BROADCAST(y) */ x FROM tbl'
Arguments:
  • hints: The SQL code strings to parse as the hints. If an Expression instance is passed, it will be used as-is.
  • dialect: The dialect used to parse the hints.
  • copy: If False, modify this expression instance in-place.
Returns:

The modified expression.

named_selects: List[str]
is_star: bool

Checks whether an expression is a star.

key = 'select'
class Subquery(DerivedTable, Unionable):
3143class Subquery(DerivedTable, Unionable):
3144    arg_types = {
3145        "this": True,
3146        "alias": False,
3147        "with": False,
3148        **QUERY_MODIFIERS,
3149    }
3150
3151    def unnest(self):
3152        """
3153        Returns the first non subquery.
3154        """
3155        expression = self
3156        while isinstance(expression, Subquery):
3157            expression = expression.this
3158        return expression
3159
3160    @property
3161    def is_star(self) -> bool:
3162        return self.this.is_star
3163
3164    @property
3165    def output_name(self) -> str:
3166        return self.alias
arg_types = {'this': True, 'alias': False, 'with': False, 'match': False, 'laterals': False, 'joins': False, 'pivots': False, 'where': False, 'group': False, 'having': False, 'qualify': False, 'windows': False, 'distribute': False, 'sort': False, 'cluster': False, 'order': False, 'limit': False, 'offset': False, 'locks': False, 'sample': False, 'settings': False, 'format': False}
def unnest(self):
3151    def unnest(self):
3152        """
3153        Returns the first non subquery.
3154        """
3155        expression = self
3156        while isinstance(expression, Subquery):
3157            expression = expression.this
3158        return expression

Returns the first non subquery.

is_star: bool

Checks whether an expression is a star.

output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'subquery'
class TableSample(Expression):
3169class TableSample(Expression):
3170    arg_types = {
3171        "this": False,
3172        "method": False,
3173        "bucket_numerator": False,
3174        "bucket_denominator": False,
3175        "bucket_field": False,
3176        "percent": False,
3177        "rows": False,
3178        "size": False,
3179        "seed": False,
3180        "kind": False,
3181    }
arg_types = {'this': False, 'method': False, 'bucket_numerator': False, 'bucket_denominator': False, 'bucket_field': False, 'percent': False, 'rows': False, 'size': False, 'seed': False, 'kind': False}
key = 'tablesample'
class Tag(Expression):
3184class Tag(Expression):
3185    """Tags are used for generating arbitrary sql like SELECT <span>x</span>."""
3186
3187    arg_types = {
3188        "this": False,
3189        "prefix": False,
3190        "postfix": False,
3191    }

Tags are used for generating arbitrary sql like SELECT x.

arg_types = {'this': False, 'prefix': False, 'postfix': False}
key = 'tag'
class Pivot(Expression):
3196class Pivot(Expression):
3197    arg_types = {
3198        "this": False,
3199        "alias": False,
3200        "expressions": True,
3201        "field": False,
3202        "unpivot": False,
3203        "using": False,
3204        "group": False,
3205        "columns": False,
3206    }
arg_types = {'this': False, 'alias': False, 'expressions': True, 'field': False, 'unpivot': False, 'using': False, 'group': False, 'columns': False}
key = 'pivot'
class Window(Expression):
3209class Window(Expression):
3210    arg_types = {
3211        "this": True,
3212        "partition_by": False,
3213        "order": False,
3214        "spec": False,
3215        "alias": False,
3216        "over": False,
3217        "first": False,
3218    }
arg_types = {'this': True, 'partition_by': False, 'order': False, 'spec': False, 'alias': False, 'over': False, 'first': False}
key = 'window'
class WindowSpec(Expression):
3221class WindowSpec(Expression):
3222    arg_types = {
3223        "kind": False,
3224        "start": False,
3225        "start_side": False,
3226        "end": False,
3227        "end_side": False,
3228    }
arg_types = {'kind': False, 'start': False, 'start_side': False, 'end': False, 'end_side': False}
key = 'windowspec'
class Where(Expression):
3231class Where(Expression):
3232    pass
key = 'where'
class Star(Expression):
3235class Star(Expression):
3236    arg_types = {"except": False, "replace": False}
3237
3238    @property
3239    def name(self) -> str:
3240        return "*"
3241
3242    @property
3243    def output_name(self) -> str:
3244        return self.name
arg_types = {'except': False, 'replace': False}
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'star'
class Parameter(Condition):
3247class Parameter(Condition):
3248    arg_types = {"this": True, "wrapped": False}
arg_types = {'this': True, 'wrapped': False}
key = 'parameter'
class SessionParameter(Condition):
3251class SessionParameter(Condition):
3252    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'sessionparameter'
class Placeholder(Condition):
3255class Placeholder(Condition):
3256    arg_types = {"this": False, "kind": False}
arg_types = {'this': False, 'kind': False}
key = 'placeholder'
class Null(Condition):
3259class Null(Condition):
3260    arg_types: t.Dict[str, t.Any] = {}
3261
3262    @property
3263    def name(self) -> str:
3264        return "NULL"
arg_types: Dict[str, Any] = {}
name: str
key = 'null'
class Boolean(Condition):
3267class Boolean(Condition):
3268    pass
key = 'boolean'
class DataTypeSize(Expression):
3271class DataTypeSize(Expression):
3272    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'datatypesize'
class DataType(Expression):
3275class DataType(Expression):
3276    arg_types = {
3277        "this": True,
3278        "expressions": False,
3279        "nested": False,
3280        "values": False,
3281        "prefix": False,
3282    }
3283
3284    class Type(AutoName):
3285        ARRAY = auto()
3286        BIGDECIMAL = auto()
3287        BIGINT = auto()
3288        BIGSERIAL = auto()
3289        BINARY = auto()
3290        BIT = auto()
3291        BOOLEAN = auto()
3292        CHAR = auto()
3293        DATE = auto()
3294        DATETIME = auto()
3295        DATETIME64 = auto()
3296        ENUM = auto()
3297        INT4RANGE = auto()
3298        INT4MULTIRANGE = auto()
3299        INT8RANGE = auto()
3300        INT8MULTIRANGE = auto()
3301        NUMRANGE = auto()
3302        NUMMULTIRANGE = auto()
3303        TSRANGE = auto()
3304        TSMULTIRANGE = auto()
3305        TSTZRANGE = auto()
3306        TSTZMULTIRANGE = auto()
3307        DATERANGE = auto()
3308        DATEMULTIRANGE = auto()
3309        DECIMAL = auto()
3310        DOUBLE = auto()
3311        FLOAT = auto()
3312        GEOGRAPHY = auto()
3313        GEOMETRY = auto()
3314        HLLSKETCH = auto()
3315        HSTORE = auto()
3316        IMAGE = auto()
3317        INET = auto()
3318        INT = auto()
3319        INT128 = auto()
3320        INT256 = auto()
3321        INTERVAL = auto()
3322        JSON = auto()
3323        JSONB = auto()
3324        LONGBLOB = auto()
3325        LONGTEXT = auto()
3326        MAP = auto()
3327        MEDIUMBLOB = auto()
3328        MEDIUMTEXT = auto()
3329        MONEY = auto()
3330        NCHAR = auto()
3331        NULL = auto()
3332        NULLABLE = auto()
3333        NVARCHAR = auto()
3334        OBJECT = auto()
3335        ROWVERSION = auto()
3336        SERIAL = auto()
3337        SET = auto()
3338        SMALLINT = auto()
3339        SMALLMONEY = auto()
3340        SMALLSERIAL = auto()
3341        STRUCT = auto()
3342        SUPER = auto()
3343        TEXT = auto()
3344        TIME = auto()
3345        TIMESTAMP = auto()
3346        TIMESTAMPTZ = auto()
3347        TIMESTAMPLTZ = auto()
3348        TINYINT = auto()
3349        UBIGINT = auto()
3350        UINT = auto()
3351        USMALLINT = auto()
3352        UTINYINT = auto()
3353        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3354        UINT128 = auto()
3355        UINT256 = auto()
3356        UNIQUEIDENTIFIER = auto()
3357        USERDEFINED = "USER-DEFINED"
3358        UUID = auto()
3359        VARBINARY = auto()
3360        VARCHAR = auto()
3361        VARIANT = auto()
3362        XML = auto()
3363
3364    TEXT_TYPES = {
3365        Type.CHAR,
3366        Type.NCHAR,
3367        Type.VARCHAR,
3368        Type.NVARCHAR,
3369        Type.TEXT,
3370    }
3371
3372    INTEGER_TYPES = {
3373        Type.INT,
3374        Type.TINYINT,
3375        Type.SMALLINT,
3376        Type.BIGINT,
3377        Type.INT128,
3378        Type.INT256,
3379    }
3380
3381    FLOAT_TYPES = {
3382        Type.FLOAT,
3383        Type.DOUBLE,
3384    }
3385
3386    NUMERIC_TYPES = {*INTEGER_TYPES, *FLOAT_TYPES}
3387
3388    TEMPORAL_TYPES = {
3389        Type.TIME,
3390        Type.TIMESTAMP,
3391        Type.TIMESTAMPTZ,
3392        Type.TIMESTAMPLTZ,
3393        Type.DATE,
3394        Type.DATETIME,
3395        Type.DATETIME64,
3396    }
3397
3398    META_TYPES = {"UNKNOWN", "NULL"}
3399
3400    @classmethod
3401    def build(
3402        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3403    ) -> DataType:
3404        from sqlglot import parse_one
3405
3406        if isinstance(dtype, str):
3407            upper = dtype.upper()
3408            if upper in DataType.META_TYPES:
3409                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3410            else:
3411                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3412
3413            if data_type_exp is None:
3414                raise ValueError(f"Unparsable data type value: {dtype}")
3415        elif isinstance(dtype, DataType.Type):
3416            data_type_exp = DataType(this=dtype)
3417        elif isinstance(dtype, DataType):
3418            return dtype
3419        else:
3420            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3421
3422        return DataType(**{**data_type_exp.args, **kwargs})
3423
3424    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3425        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
arg_types = {'this': True, 'expressions': False, 'nested': False, 'values': False, 'prefix': False}
TEXT_TYPES = {<Type.CHAR: 'CHAR'>, <Type.NCHAR: 'NCHAR'>, <Type.VARCHAR: 'VARCHAR'>, <Type.TEXT: 'TEXT'>, <Type.NVARCHAR: 'NVARCHAR'>}
INTEGER_TYPES = {<Type.INT256: 'INT256'>, <Type.INT: 'INT'>, <Type.BIGINT: 'BIGINT'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.TINYINT: 'TINYINT'>}
FLOAT_TYPES = {<Type.FLOAT: 'FLOAT'>, <Type.DOUBLE: 'DOUBLE'>}
NUMERIC_TYPES = {<Type.BIGINT: 'BIGINT'>, <Type.FLOAT: 'FLOAT'>, <Type.INT256: 'INT256'>, <Type.DOUBLE: 'DOUBLE'>, <Type.SMALLINT: 'SMALLINT'>, <Type.INT128: 'INT128'>, <Type.TINYINT: 'TINYINT'>, <Type.INT: 'INT'>}
TEMPORAL_TYPES = {<Type.TIME: 'TIME'>, <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>, <Type.DATETIME64: 'DATETIME64'>, <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>, <Type.TIMESTAMP: 'TIMESTAMP'>, <Type.DATETIME: 'DATETIME'>, <Type.DATE: 'DATE'>}
META_TYPES = {'UNKNOWN', 'NULL'}
@classmethod
def build( cls, dtype: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.DataType:
3400    @classmethod
3401    def build(
3402        cls, dtype: str | DataType | DataType.Type, dialect: DialectType = None, **kwargs
3403    ) -> DataType:
3404        from sqlglot import parse_one
3405
3406        if isinstance(dtype, str):
3407            upper = dtype.upper()
3408            if upper in DataType.META_TYPES:
3409                data_type_exp: t.Optional[Expression] = DataType(this=DataType.Type[upper])
3410            else:
3411                data_type_exp = parse_one(dtype, read=dialect, into=DataType)
3412
3413            if data_type_exp is None:
3414                raise ValueError(f"Unparsable data type value: {dtype}")
3415        elif isinstance(dtype, DataType.Type):
3416            data_type_exp = DataType(this=dtype)
3417        elif isinstance(dtype, DataType):
3418            return dtype
3419        else:
3420            raise ValueError(f"Invalid data type: {type(dtype)}. Expected str or DataType.Type")
3421
3422        return DataType(**{**data_type_exp.args, **kwargs})
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3424    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3425        return any(self.this == DataType.build(dtype).this for dtype in dtypes)
key = 'datatype'
class DataType.Type(sqlglot.helper.AutoName):
3284    class Type(AutoName):
3285        ARRAY = auto()
3286        BIGDECIMAL = auto()
3287        BIGINT = auto()
3288        BIGSERIAL = auto()
3289        BINARY = auto()
3290        BIT = auto()
3291        BOOLEAN = auto()
3292        CHAR = auto()
3293        DATE = auto()
3294        DATETIME = auto()
3295        DATETIME64 = auto()
3296        ENUM = auto()
3297        INT4RANGE = auto()
3298        INT4MULTIRANGE = auto()
3299        INT8RANGE = auto()
3300        INT8MULTIRANGE = auto()
3301        NUMRANGE = auto()
3302        NUMMULTIRANGE = auto()
3303        TSRANGE = auto()
3304        TSMULTIRANGE = auto()
3305        TSTZRANGE = auto()
3306        TSTZMULTIRANGE = auto()
3307        DATERANGE = auto()
3308        DATEMULTIRANGE = auto()
3309        DECIMAL = auto()
3310        DOUBLE = auto()
3311        FLOAT = auto()
3312        GEOGRAPHY = auto()
3313        GEOMETRY = auto()
3314        HLLSKETCH = auto()
3315        HSTORE = auto()
3316        IMAGE = auto()
3317        INET = auto()
3318        INT = auto()
3319        INT128 = auto()
3320        INT256 = auto()
3321        INTERVAL = auto()
3322        JSON = auto()
3323        JSONB = auto()
3324        LONGBLOB = auto()
3325        LONGTEXT = auto()
3326        MAP = auto()
3327        MEDIUMBLOB = auto()
3328        MEDIUMTEXT = auto()
3329        MONEY = auto()
3330        NCHAR = auto()
3331        NULL = auto()
3332        NULLABLE = auto()
3333        NVARCHAR = auto()
3334        OBJECT = auto()
3335        ROWVERSION = auto()
3336        SERIAL = auto()
3337        SET = auto()
3338        SMALLINT = auto()
3339        SMALLMONEY = auto()
3340        SMALLSERIAL = auto()
3341        STRUCT = auto()
3342        SUPER = auto()
3343        TEXT = auto()
3344        TIME = auto()
3345        TIMESTAMP = auto()
3346        TIMESTAMPTZ = auto()
3347        TIMESTAMPLTZ = auto()
3348        TINYINT = auto()
3349        UBIGINT = auto()
3350        UINT = auto()
3351        USMALLINT = auto()
3352        UTINYINT = auto()
3353        UNKNOWN = auto()  # Sentinel value, useful for type annotation
3354        UINT128 = auto()
3355        UINT256 = auto()
3356        UNIQUEIDENTIFIER = auto()
3357        USERDEFINED = "USER-DEFINED"
3358        UUID = auto()
3359        VARBINARY = auto()
3360        VARCHAR = auto()
3361        VARIANT = auto()
3362        XML = auto()

An enumeration.

ARRAY = <Type.ARRAY: 'ARRAY'>
BIGDECIMAL = <Type.BIGDECIMAL: 'BIGDECIMAL'>
BIGINT = <Type.BIGINT: 'BIGINT'>
BIGSERIAL = <Type.BIGSERIAL: 'BIGSERIAL'>
BINARY = <Type.BINARY: 'BINARY'>
BIT = <Type.BIT: 'BIT'>
BOOLEAN = <Type.BOOLEAN: 'BOOLEAN'>
CHAR = <Type.CHAR: 'CHAR'>
DATE = <Type.DATE: 'DATE'>
DATETIME = <Type.DATETIME: 'DATETIME'>
DATETIME64 = <Type.DATETIME64: 'DATETIME64'>
ENUM = <Type.ENUM: 'ENUM'>
INT4RANGE = <Type.INT4RANGE: 'INT4RANGE'>
INT4MULTIRANGE = <Type.INT4MULTIRANGE: 'INT4MULTIRANGE'>
INT8RANGE = <Type.INT8RANGE: 'INT8RANGE'>
INT8MULTIRANGE = <Type.INT8MULTIRANGE: 'INT8MULTIRANGE'>
NUMRANGE = <Type.NUMRANGE: 'NUMRANGE'>
NUMMULTIRANGE = <Type.NUMMULTIRANGE: 'NUMMULTIRANGE'>
TSRANGE = <Type.TSRANGE: 'TSRANGE'>
TSMULTIRANGE = <Type.TSMULTIRANGE: 'TSMULTIRANGE'>
TSTZRANGE = <Type.TSTZRANGE: 'TSTZRANGE'>
TSTZMULTIRANGE = <Type.TSTZMULTIRANGE: 'TSTZMULTIRANGE'>
DATERANGE = <Type.DATERANGE: 'DATERANGE'>
DATEMULTIRANGE = <Type.DATEMULTIRANGE: 'DATEMULTIRANGE'>
DECIMAL = <Type.DECIMAL: 'DECIMAL'>
DOUBLE = <Type.DOUBLE: 'DOUBLE'>
FLOAT = <Type.FLOAT: 'FLOAT'>
GEOGRAPHY = <Type.GEOGRAPHY: 'GEOGRAPHY'>
GEOMETRY = <Type.GEOMETRY: 'GEOMETRY'>
HLLSKETCH = <Type.HLLSKETCH: 'HLLSKETCH'>
HSTORE = <Type.HSTORE: 'HSTORE'>
IMAGE = <Type.IMAGE: 'IMAGE'>
INET = <Type.INET: 'INET'>
INT = <Type.INT: 'INT'>
INT128 = <Type.INT128: 'INT128'>
INT256 = <Type.INT256: 'INT256'>
INTERVAL = <Type.INTERVAL: 'INTERVAL'>
JSON = <Type.JSON: 'JSON'>
JSONB = <Type.JSONB: 'JSONB'>
LONGBLOB = <Type.LONGBLOB: 'LONGBLOB'>
LONGTEXT = <Type.LONGTEXT: 'LONGTEXT'>
MAP = <Type.MAP: 'MAP'>
MEDIUMBLOB = <Type.MEDIUMBLOB: 'MEDIUMBLOB'>
MEDIUMTEXT = <Type.MEDIUMTEXT: 'MEDIUMTEXT'>
MONEY = <Type.MONEY: 'MONEY'>
NCHAR = <Type.NCHAR: 'NCHAR'>
NULL = <Type.NULL: 'NULL'>
NULLABLE = <Type.NULLABLE: 'NULLABLE'>
NVARCHAR = <Type.NVARCHAR: 'NVARCHAR'>
OBJECT = <Type.OBJECT: 'OBJECT'>
ROWVERSION = <Type.ROWVERSION: 'ROWVERSION'>
SERIAL = <Type.SERIAL: 'SERIAL'>
SET = <Type.SET: 'SET'>
SMALLINT = <Type.SMALLINT: 'SMALLINT'>
SMALLMONEY = <Type.SMALLMONEY: 'SMALLMONEY'>
SMALLSERIAL = <Type.SMALLSERIAL: 'SMALLSERIAL'>
STRUCT = <Type.STRUCT: 'STRUCT'>
SUPER = <Type.SUPER: 'SUPER'>
TEXT = <Type.TEXT: 'TEXT'>
TIME = <Type.TIME: 'TIME'>
TIMESTAMP = <Type.TIMESTAMP: 'TIMESTAMP'>
TIMESTAMPTZ = <Type.TIMESTAMPTZ: 'TIMESTAMPTZ'>
TIMESTAMPLTZ = <Type.TIMESTAMPLTZ: 'TIMESTAMPLTZ'>
TINYINT = <Type.TINYINT: 'TINYINT'>
UBIGINT = <Type.UBIGINT: 'UBIGINT'>
UINT = <Type.UINT: 'UINT'>
USMALLINT = <Type.USMALLINT: 'USMALLINT'>
UTINYINT = <Type.UTINYINT: 'UTINYINT'>
UNKNOWN = <Type.UNKNOWN: 'UNKNOWN'>
UINT128 = <Type.UINT128: 'UINT128'>
UINT256 = <Type.UINT256: 'UINT256'>
UNIQUEIDENTIFIER = <Type.UNIQUEIDENTIFIER: 'UNIQUEIDENTIFIER'>
USERDEFINED = <Type.USERDEFINED: 'USER-DEFINED'>
UUID = <Type.UUID: 'UUID'>
VARBINARY = <Type.VARBINARY: 'VARBINARY'>
VARCHAR = <Type.VARCHAR: 'VARCHAR'>
VARIANT = <Type.VARIANT: 'VARIANT'>
XML = <Type.XML: 'XML'>
Inherited Members
enum.Enum
name
value
class PseudoType(Expression):
3429class PseudoType(Expression):
3430    pass
key = 'pseudotype'
class SubqueryPredicate(Predicate):
3434class SubqueryPredicate(Predicate):
3435    pass
key = 'subquerypredicate'
class All(SubqueryPredicate):
3438class All(SubqueryPredicate):
3439    pass
key = 'all'
class Any(SubqueryPredicate):
3442class Any(SubqueryPredicate):
3443    pass
key = 'any'
class Exists(SubqueryPredicate):
3446class Exists(SubqueryPredicate):
3447    pass
key = 'exists'
class Command(Expression):
3452class Command(Expression):
3453    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'command'
class Transaction(Expression):
3456class Transaction(Expression):
3457    arg_types = {"this": False, "modes": False}
arg_types = {'this': False, 'modes': False}
key = 'transaction'
class Commit(Expression):
3460class Commit(Expression):
3461    arg_types = {"chain": False}
arg_types = {'chain': False}
key = 'commit'
class Rollback(Expression):
3464class Rollback(Expression):
3465    arg_types = {"savepoint": False}
arg_types = {'savepoint': False}
key = 'rollback'
class AlterTable(Expression):
3468class AlterTable(Expression):
3469    arg_types = {"this": True, "actions": True, "exists": False}
arg_types = {'this': True, 'actions': True, 'exists': False}
key = 'altertable'
class AddConstraint(Expression):
3472class AddConstraint(Expression):
3473    arg_types = {"this": False, "expression": False, "enforced": False}
arg_types = {'this': False, 'expression': False, 'enforced': False}
key = 'addconstraint'
class DropPartition(Expression):
3476class DropPartition(Expression):
3477    arg_types = {"expressions": True, "exists": False}
arg_types = {'expressions': True, 'exists': False}
key = 'droppartition'
class Binary(Condition):
3481class Binary(Condition):
3482    arg_types = {"this": True, "expression": True}
3483
3484    @property
3485    def left(self):
3486        return self.this
3487
3488    @property
3489    def right(self):
3490        return self.expression
arg_types = {'this': True, 'expression': True}
left
right
key = 'binary'
class Add(Binary):
3493class Add(Binary):
3494    pass
key = 'add'
class Connector(Binary):
3497class Connector(Binary):
3498    pass
key = 'connector'
class And(Connector):
3501class And(Connector):
3502    pass
key = 'and'
class Or(Connector):
3505class Or(Connector):
3506    pass
key = 'or'
class BitwiseAnd(Binary):
3509class BitwiseAnd(Binary):
3510    pass
key = 'bitwiseand'
class BitwiseLeftShift(Binary):
3513class BitwiseLeftShift(Binary):
3514    pass
key = 'bitwiseleftshift'
class BitwiseOr(Binary):
3517class BitwiseOr(Binary):
3518    pass
key = 'bitwiseor'
class BitwiseRightShift(Binary):
3521class BitwiseRightShift(Binary):
3522    pass
key = 'bitwiserightshift'
class BitwiseXor(Binary):
3525class BitwiseXor(Binary):
3526    pass
key = 'bitwisexor'
class Div(Binary):
3529class Div(Binary):
3530    pass
key = 'div'
class Overlaps(Binary):
3533class Overlaps(Binary):
3534    pass
key = 'overlaps'
class Dot(Binary):
3537class Dot(Binary):
3538    @property
3539    def name(self) -> str:
3540        return self.expression.name
3541
3542    @property
3543    def output_name(self) -> str:
3544        return self.name
3545
3546    @classmethod
3547    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3548        """Build a Dot object with a sequence of expressions."""
3549        if len(expressions) < 2:
3550            raise ValueError(f"Dot requires >= 2 expressions.")
3551
3552        a, b, *expressions = expressions
3553        dot = Dot(this=a, expression=b)
3554
3555        for expression in expressions:
3556            dot = Dot(this=dot, expression=expression)
3557
3558        return dot
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
@classmethod
def build( self, expressions: Sequence[sqlglot.expressions.Expression]) -> sqlglot.expressions.Dot:
3546    @classmethod
3547    def build(self, expressions: t.Sequence[Expression]) -> Dot:
3548        """Build a Dot object with a sequence of expressions."""
3549        if len(expressions) < 2:
3550            raise ValueError(f"Dot requires >= 2 expressions.")
3551
3552        a, b, *expressions = expressions
3553        dot = Dot(this=a, expression=b)
3554
3555        for expression in expressions:
3556            dot = Dot(this=dot, expression=expression)
3557
3558        return dot

Build a Dot object with a sequence of expressions.

key = 'dot'
class DPipe(Binary):
3561class DPipe(Binary):
3562    pass
key = 'dpipe'
class SafeDPipe(DPipe):
3565class SafeDPipe(DPipe):
3566    pass
key = 'safedpipe'
class EQ(Binary, Predicate):
3569class EQ(Binary, Predicate):
3570    pass
key = 'eq'
class NullSafeEQ(Binary, Predicate):
3573class NullSafeEQ(Binary, Predicate):
3574    pass
key = 'nullsafeeq'
class NullSafeNEQ(Binary, Predicate):
3577class NullSafeNEQ(Binary, Predicate):
3578    pass
key = 'nullsafeneq'
class Distance(Binary):
3581class Distance(Binary):
3582    pass
key = 'distance'
class Escape(Binary):
3585class Escape(Binary):
3586    pass
key = 'escape'
class Glob(Binary, Predicate):
3589class Glob(Binary, Predicate):
3590    pass
key = 'glob'
class GT(Binary, Predicate):
3593class GT(Binary, Predicate):
3594    pass
key = 'gt'
class GTE(Binary, Predicate):
3597class GTE(Binary, Predicate):
3598    pass
key = 'gte'
class ILike(Binary, Predicate):
3601class ILike(Binary, Predicate):
3602    pass
key = 'ilike'
class ILikeAny(Binary, Predicate):
3605class ILikeAny(Binary, Predicate):
3606    pass
key = 'ilikeany'
class IntDiv(Binary):
3609class IntDiv(Binary):
3610    pass
key = 'intdiv'
class Is(Binary, Predicate):
3613class Is(Binary, Predicate):
3614    pass
key = 'is'
class Kwarg(Binary):
3617class Kwarg(Binary):
3618    """Kwarg in special functions like func(kwarg => y)."""

Kwarg in special functions like func(kwarg => y).

key = 'kwarg'
class Like(Binary, Predicate):
3621class Like(Binary, Predicate):
3622    pass
key = 'like'
class LikeAny(Binary, Predicate):
3625class LikeAny(Binary, Predicate):
3626    pass
key = 'likeany'
class LT(Binary, Predicate):
3629class LT(Binary, Predicate):
3630    pass
key = 'lt'
class LTE(Binary, Predicate):
3633class LTE(Binary, Predicate):
3634    pass
key = 'lte'
class Mod(Binary):
3637class Mod(Binary):
3638    pass
key = 'mod'
class Mul(Binary):
3641class Mul(Binary):
3642    pass
key = 'mul'
class NEQ(Binary, Predicate):
3645class NEQ(Binary, Predicate):
3646    pass
key = 'neq'
class SimilarTo(Binary, Predicate):
3649class SimilarTo(Binary, Predicate):
3650    pass
key = 'similarto'
class Slice(Binary):
3653class Slice(Binary):
3654    arg_types = {"this": False, "expression": False}
arg_types = {'this': False, 'expression': False}
key = 'slice'
class Sub(Binary):
3657class Sub(Binary):
3658    pass
key = 'sub'
class ArrayOverlaps(Binary):
3661class ArrayOverlaps(Binary):
3662    pass
key = 'arrayoverlaps'
class Unary(Condition):
3667class Unary(Condition):
3668    pass
key = 'unary'
class BitwiseNot(Unary):
3671class BitwiseNot(Unary):
3672    pass
key = 'bitwisenot'
class Not(Unary):
3675class Not(Unary):
3676    pass
key = 'not'
class Paren(Unary):
3679class Paren(Unary):
3680    arg_types = {"this": True, "with": False}
3681
3682    @property
3683    def output_name(self) -> str:
3684        return self.this.name
arg_types = {'this': True, 'with': False}
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'paren'
class Neg(Unary):
3687class Neg(Unary):
3688    pass
key = 'neg'
class Alias(Expression):
3691class Alias(Expression):
3692    arg_types = {"this": True, "alias": False}
3693
3694    @property
3695    def output_name(self) -> str:
3696        return self.alias
arg_types = {'this': True, 'alias': False}
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
key = 'alias'
class Aliases(Expression):
3699class Aliases(Expression):
3700    arg_types = {"this": True, "expressions": True}
3701
3702    @property
3703    def aliases(self):
3704        return self.expressions
arg_types = {'this': True, 'expressions': True}
aliases
key = 'aliases'
class AtTimeZone(Expression):
3707class AtTimeZone(Expression):
3708    arg_types = {"this": True, "zone": True}
arg_types = {'this': True, 'zone': True}
key = 'attimezone'
class Between(Predicate):
3711class Between(Predicate):
3712    arg_types = {"this": True, "low": True, "high": True}
arg_types = {'this': True, 'low': True, 'high': True}
key = 'between'
class Bracket(Condition):
3715class Bracket(Condition):
3716    arg_types = {"this": True, "expressions": True}
arg_types = {'this': True, 'expressions': True}
key = 'bracket'
class Distinct(Expression):
3719class Distinct(Expression):
3720    arg_types = {"expressions": False, "on": False}
arg_types = {'expressions': False, 'on': False}
key = 'distinct'
class In(Predicate):
3723class In(Predicate):
3724    arg_types = {
3725        "this": True,
3726        "expressions": False,
3727        "query": False,
3728        "unnest": False,
3729        "field": False,
3730        "is_global": False,
3731    }
arg_types = {'this': True, 'expressions': False, 'query': False, 'unnest': False, 'field': False, 'is_global': False}
key = 'in'
class TimeUnit(Expression):
3734class TimeUnit(Expression):
3735    """Automatically converts unit arg into a var."""
3736
3737    arg_types = {"unit": False}
3738
3739    def __init__(self, **args):
3740        unit = args.get("unit")
3741        if isinstance(unit, (Column, Literal)):
3742            args["unit"] = Var(this=unit.name)
3743        elif isinstance(unit, Week):
3744            unit.set("this", Var(this=unit.this.name))
3745
3746        super().__init__(**args)

Automatically converts unit arg into a var.

TimeUnit(**args)
3739    def __init__(self, **args):
3740        unit = args.get("unit")
3741        if isinstance(unit, (Column, Literal)):
3742            args["unit"] = Var(this=unit.name)
3743        elif isinstance(unit, Week):
3744            unit.set("this", Var(this=unit.this.name))
3745
3746        super().__init__(**args)
arg_types = {'unit': False}
key = 'timeunit'
class Interval(TimeUnit):
3749class Interval(TimeUnit):
3750    arg_types = {"this": False, "unit": False}
3751
3752    @property
3753    def unit(self) -> t.Optional[Var]:
3754        return self.args.get("unit")
arg_types = {'this': False, 'unit': False}
unit: Optional[sqlglot.expressions.Var]
key = 'interval'
class IgnoreNulls(Expression):
3757class IgnoreNulls(Expression):
3758    pass
key = 'ignorenulls'
class RespectNulls(Expression):
3761class RespectNulls(Expression):
3762    pass
key = 'respectnulls'
class Func(Condition):
3766class Func(Condition):
3767    """
3768    The base class for all function expressions.
3769
3770    Attributes:
3771        is_var_len_args (bool): if set to True the last argument defined in arg_types will be
3772            treated as a variable length argument and the argument's value will be stored as a list.
3773        _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items)
3774            for this function expression. These values are used to map this node to a name during parsing
3775            as well as to provide the function's name during SQL string generation. By default the SQL
3776            name is set to the expression's class name transformed to snake case.
3777    """
3778
3779    is_var_len_args = False
3780
3781    @classmethod
3782    def from_arg_list(cls, args):
3783        if cls.is_var_len_args:
3784            all_arg_keys = list(cls.arg_types)
3785            # If this function supports variable length argument treat the last argument as such.
3786            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3787            num_non_var = len(non_var_len_arg_keys)
3788
3789            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3790            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3791        else:
3792            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3793
3794        return cls(**args_dict)
3795
3796    @classmethod
3797    def sql_names(cls):
3798        if cls is Func:
3799            raise NotImplementedError(
3800                "SQL name is only supported by concrete function implementations"
3801            )
3802        if "_sql_names" not in cls.__dict__:
3803            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3804        return cls._sql_names
3805
3806    @classmethod
3807    def sql_name(cls):
3808        return cls.sql_names()[0]
3809
3810    @classmethod
3811    def default_parser_mappings(cls):
3812        return {name: cls.from_arg_list for name in cls.sql_names()}

The base class for all function expressions.

Attributes:
  • is_var_len_args (bool): if set to True the last argument defined in arg_types will be treated as a variable length argument and the argument's value will be stored as a list.
  • _sql_names (list): determines the SQL name (1st item in the list) and aliases (subsequent items) for this function expression. These values are used to map this node to a name during parsing as well as to provide the function's name during SQL string generation. By default the SQL name is set to the expression's class name transformed to snake case.
is_var_len_args = False
@classmethod
def from_arg_list(cls, args):
3781    @classmethod
3782    def from_arg_list(cls, args):
3783        if cls.is_var_len_args:
3784            all_arg_keys = list(cls.arg_types)
3785            # If this function supports variable length argument treat the last argument as such.
3786            non_var_len_arg_keys = all_arg_keys[:-1] if cls.is_var_len_args else all_arg_keys
3787            num_non_var = len(non_var_len_arg_keys)
3788
3789            args_dict = {arg_key: arg for arg, arg_key in zip(args, non_var_len_arg_keys)}
3790            args_dict[all_arg_keys[-1]] = args[num_non_var:]
3791        else:
3792            args_dict = {arg_key: arg for arg, arg_key in zip(args, cls.arg_types)}
3793
3794        return cls(**args_dict)
@classmethod
def sql_names(cls):
3796    @classmethod
3797    def sql_names(cls):
3798        if cls is Func:
3799            raise NotImplementedError(
3800                "SQL name is only supported by concrete function implementations"
3801            )
3802        if "_sql_names" not in cls.__dict__:
3803            cls._sql_names = [camel_to_snake_case(cls.__name__)]
3804        return cls._sql_names
@classmethod
def sql_name(cls):
3806    @classmethod
3807    def sql_name(cls):
3808        return cls.sql_names()[0]
@classmethod
def default_parser_mappings(cls):
3810    @classmethod
3811    def default_parser_mappings(cls):
3812        return {name: cls.from_arg_list for name in cls.sql_names()}
key = 'func'
class AggFunc(Func):
3815class AggFunc(Func):
3816    pass
key = 'aggfunc'
class ParameterizedAgg(AggFunc):
3819class ParameterizedAgg(AggFunc):
3820    arg_types = {"this": True, "expressions": True, "params": True}
arg_types = {'this': True, 'expressions': True, 'params': True}
key = 'parameterizedagg'
class Abs(Func):
3823class Abs(Func):
3824    pass
key = 'abs'
class Anonymous(Func):
3827class Anonymous(Func):
3828    arg_types = {"this": True, "expressions": False}
3829    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'anonymous'
class Hll(AggFunc):
3834class Hll(AggFunc):
3835    arg_types = {"this": True, "expressions": False}
3836    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'hll'
class ApproxDistinct(AggFunc):
3839class ApproxDistinct(AggFunc):
3840    arg_types = {"this": True, "accuracy": False}
3841    _sql_names = ["APPROX_DISTINCT", "APPROX_COUNT_DISTINCT"]
arg_types = {'this': True, 'accuracy': False}
key = 'approxdistinct'
class Array(Func):
3844class Array(Func):
3845    arg_types = {"expressions": False}
3846    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'array'
class ToChar(Func):
3850class ToChar(Func):
3851    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tochar'
class GenerateSeries(Func):
3854class GenerateSeries(Func):
3855    arg_types = {"start": True, "end": True, "step": False}
arg_types = {'start': True, 'end': True, 'step': False}
key = 'generateseries'
class ArrayAgg(AggFunc):
3858class ArrayAgg(AggFunc):
3859    pass
key = 'arrayagg'
class ArrayAll(Func):
3862class ArrayAll(Func):
3863    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayall'
class ArrayAny(Func):
3866class ArrayAny(Func):
3867    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'arrayany'
class ArrayConcat(Func):
3870class ArrayConcat(Func):
3871    arg_types = {"this": True, "expressions": False}
3872    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'arrayconcat'
class ArrayContains(Binary, Func):
3875class ArrayContains(Binary, Func):
3876    pass
key = 'arraycontains'
class ArrayContained(Binary):
3879class ArrayContained(Binary):
3880    pass
key = 'arraycontained'
class ArrayFilter(Func):
3883class ArrayFilter(Func):
3884    arg_types = {"this": True, "expression": True}
3885    _sql_names = ["FILTER", "ARRAY_FILTER"]
arg_types = {'this': True, 'expression': True}
key = 'arrayfilter'
class ArrayJoin(Func):
3888class ArrayJoin(Func):
3889    arg_types = {"this": True, "expression": True, "null": False}
arg_types = {'this': True, 'expression': True, 'null': False}
key = 'arrayjoin'
class ArraySize(Func):
3892class ArraySize(Func):
3893    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysize'
class ArraySort(Func):
3896class ArraySort(Func):
3897    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'arraysort'
class ArraySum(Func):
3900class ArraySum(Func):
3901    pass
key = 'arraysum'
class ArrayUnionAgg(AggFunc):
3904class ArrayUnionAgg(AggFunc):
3905    pass
key = 'arrayunionagg'
class Avg(AggFunc):
3908class Avg(AggFunc):
3909    pass
key = 'avg'
class AnyValue(AggFunc):
3912class AnyValue(AggFunc):
3913    pass
key = 'anyvalue'
class Case(Func):
3916class Case(Func):
3917    arg_types = {"this": False, "ifs": True, "default": False}
3918
3919    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3920        instance = _maybe_copy(self, copy)
3921        instance.append(
3922            "ifs",
3923            If(
3924                this=maybe_parse(condition, copy=copy, **opts),
3925                true=maybe_parse(then, copy=copy, **opts),
3926            ),
3927        )
3928        return instance
3929
3930    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3931        instance = _maybe_copy(self, copy)
3932        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3933        return instance
arg_types = {'this': False, 'ifs': True, 'default': False}
def when( self, condition: Union[str, sqlglot.expressions.Expression], then: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3919    def when(self, condition: ExpOrStr, then: ExpOrStr, copy: bool = True, **opts) -> Case:
3920        instance = _maybe_copy(self, copy)
3921        instance.append(
3922            "ifs",
3923            If(
3924                this=maybe_parse(condition, copy=copy, **opts),
3925                true=maybe_parse(then, copy=copy, **opts),
3926            ),
3927        )
3928        return instance
def else_( self, condition: Union[str, sqlglot.expressions.Expression], copy: bool = True, **opts) -> sqlglot.expressions.Case:
3930    def else_(self, condition: ExpOrStr, copy: bool = True, **opts) -> Case:
3931        instance = _maybe_copy(self, copy)
3932        instance.set("default", maybe_parse(condition, copy=copy, **opts))
3933        return instance
key = 'case'
class Cast(Func):
3936class Cast(Func):
3937    arg_types = {"this": True, "to": True}
3938
3939    @property
3940    def name(self) -> str:
3941        return self.this.name
3942
3943    @property
3944    def to(self) -> DataType:
3945        return self.args["to"]
3946
3947    @property
3948    def output_name(self) -> str:
3949        return self.name
3950
3951    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3952        return self.to.is_type(*dtypes)
arg_types = {'this': True, 'to': True}
name: str
output_name: str

Name of the output column if this expression is a selection.

If the Expression has no output name, an empty string is returned.

Example:
>>> from sqlglot import parse_one
>>> parse_one("SELECT a").expressions[0].output_name
'a'
>>> parse_one("SELECT b AS c").expressions[0].output_name
'c'
>>> parse_one("SELECT 1 + 2").expressions[0].output_name
''
def is_type( self, *dtypes: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type) -> bool:
3951    def is_type(self, *dtypes: str | DataType | DataType.Type) -> bool:
3952        return self.to.is_type(*dtypes)
key = 'cast'
class CastToStrType(Func):
3955class CastToStrType(Func):
3956    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'casttostrtype'
class Collate(Binary):
3959class Collate(Binary):
3960    pass
key = 'collate'
class TryCast(Cast):
3963class TryCast(Cast):
3964    pass
key = 'trycast'
class Ceil(Func):
3967class Ceil(Func):
3968    arg_types = {"this": True, "decimals": False}
3969    _sql_names = ["CEIL", "CEILING"]
arg_types = {'this': True, 'decimals': False}
key = 'ceil'
class Coalesce(Func):
3972class Coalesce(Func):
3973    arg_types = {"this": True, "expressions": False}
3974    is_var_len_args = True
3975    _sql_names = ["COALESCE", "IFNULL", "NVL"]
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'coalesce'
class Concat(Func):
3978class Concat(Func):
3979    arg_types = {"expressions": True}
3980    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'concat'
class SafeConcat(Concat):
3983class SafeConcat(Concat):
3984    pass
key = 'safeconcat'
class ConcatWs(Concat):
3987class ConcatWs(Concat):
3988    _sql_names = ["CONCAT_WS"]
key = 'concatws'
class Count(AggFunc):
3991class Count(AggFunc):
3992    arg_types = {"this": False, "expressions": False}
3993    is_var_len_args = True
arg_types = {'this': False, 'expressions': False}
is_var_len_args = True
key = 'count'
class CountIf(AggFunc):
3996class CountIf(AggFunc):
3997    pass
key = 'countif'
class CurrentDate(Func):
4000class CurrentDate(Func):
4001    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdate'
class CurrentDatetime(Func):
4004class CurrentDatetime(Func):
4005    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentdatetime'
class CurrentTime(Func):
4008class CurrentTime(Func):
4009    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttime'
class CurrentTimestamp(Func):
4012class CurrentTimestamp(Func):
4013    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currenttimestamp'
class CurrentUser(Func):
4016class CurrentUser(Func):
4017    arg_types = {"this": False}
arg_types = {'this': False}
key = 'currentuser'
class DateAdd(Func, TimeUnit):
4020class DateAdd(Func, TimeUnit):
4021    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'dateadd'
class DateSub(Func, TimeUnit):
4024class DateSub(Func, TimeUnit):
4025    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datesub'
class DateDiff(Func, TimeUnit):
4028class DateDiff(Func, TimeUnit):
4029    _sql_names = ["DATEDIFF", "DATE_DIFF"]
4030    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datediff'
class DateTrunc(Func):
4033class DateTrunc(Func):
4034    arg_types = {"unit": True, "this": True, "zone": False}
arg_types = {'unit': True, 'this': True, 'zone': False}
key = 'datetrunc'
class DatetimeAdd(Func, TimeUnit):
4037class DatetimeAdd(Func, TimeUnit):
4038    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimeadd'
class DatetimeSub(Func, TimeUnit):
4041class DatetimeSub(Func, TimeUnit):
4042    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimesub'
class DatetimeDiff(Func, TimeUnit):
4045class DatetimeDiff(Func, TimeUnit):
4046    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'datetimediff'
class DatetimeTrunc(Func, TimeUnit):
4049class DatetimeTrunc(Func, TimeUnit):
4050    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'datetimetrunc'
class DayOfWeek(Func):
4053class DayOfWeek(Func):
4054    _sql_names = ["DAY_OF_WEEK", "DAYOFWEEK"]
key = 'dayofweek'
class DayOfMonth(Func):
4057class DayOfMonth(Func):
4058    _sql_names = ["DAY_OF_MONTH", "DAYOFMONTH"]
key = 'dayofmonth'
class DayOfYear(Func):
4061class DayOfYear(Func):
4062    _sql_names = ["DAY_OF_YEAR", "DAYOFYEAR"]
key = 'dayofyear'
class WeekOfYear(Func):
4065class WeekOfYear(Func):
4066    _sql_names = ["WEEK_OF_YEAR", "WEEKOFYEAR"]
key = 'weekofyear'
class LastDateOfMonth(Func):
4069class LastDateOfMonth(Func):
4070    pass
key = 'lastdateofmonth'
class Extract(Func):
4073class Extract(Func):
4074    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'extract'
class TimestampAdd(Func, TimeUnit):
4077class TimestampAdd(Func, TimeUnit):
4078    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampadd'
class TimestampSub(Func, TimeUnit):
4081class TimestampSub(Func, TimeUnit):
4082    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampsub'
class TimestampDiff(Func, TimeUnit):
4085class TimestampDiff(Func, TimeUnit):
4086    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timestampdiff'
class TimestampTrunc(Func, TimeUnit):
4089class TimestampTrunc(Func, TimeUnit):
4090    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timestamptrunc'
class TimeAdd(Func, TimeUnit):
4093class TimeAdd(Func, TimeUnit):
4094    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timeadd'
class TimeSub(Func, TimeUnit):
4097class TimeSub(Func, TimeUnit):
4098    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timesub'
class TimeDiff(Func, TimeUnit):
4101class TimeDiff(Func, TimeUnit):
4102    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'timediff'
class TimeTrunc(Func, TimeUnit):
4105class TimeTrunc(Func, TimeUnit):
4106    arg_types = {"this": True, "unit": True, "zone": False}
arg_types = {'this': True, 'unit': True, 'zone': False}
key = 'timetrunc'
class DateFromParts(Func):
4109class DateFromParts(Func):
4110    _sql_names = ["DATEFROMPARTS"]
4111    arg_types = {"year": True, "month": True, "day": True}
arg_types = {'year': True, 'month': True, 'day': True}
key = 'datefromparts'
class DateStrToDate(Func):
4114class DateStrToDate(Func):
4115    pass
key = 'datestrtodate'
class DateToDateStr(Func):
4118class DateToDateStr(Func):
4119    pass
key = 'datetodatestr'
class DateToDi(Func):
4122class DateToDi(Func):
4123    pass
key = 'datetodi'
class Date(Func):
4126class Date(Func):
4127    arg_types = {"expressions": True}
4128    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'date'
class Day(Func):
4131class Day(Func):
4132    pass
key = 'day'
class Decode(Func):
4135class Decode(Func):
4136    arg_types = {"this": True, "charset": True, "replace": False}
arg_types = {'this': True, 'charset': True, 'replace': False}
key = 'decode'
class DiToDate(Func):
4139class DiToDate(Func):
4140    pass
key = 'ditodate'
class Encode(Func):
4143class Encode(Func):
4144    arg_types = {"this": True, "charset": True}
arg_types = {'this': True, 'charset': True}
key = 'encode'
class Exp(Func):
4147class Exp(Func):
4148    pass
key = 'exp'
class Explode(Func):
4151class Explode(Func):
4152    pass
key = 'explode'
class Floor(Func):
4155class Floor(Func):
4156    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'floor'
class FromBase64(Func):
4159class FromBase64(Func):
4160    pass
key = 'frombase64'
class ToBase64(Func):
4163class ToBase64(Func):
4164    pass
key = 'tobase64'
class Greatest(Func):
4167class Greatest(Func):
4168    arg_types = {"this": True, "expressions": False}
4169    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'greatest'
class GroupConcat(Func):
4172class GroupConcat(Func):
4173    arg_types = {"this": True, "separator": False}
arg_types = {'this': True, 'separator': False}
key = 'groupconcat'
class Hex(Func):
4176class Hex(Func):
4177    pass
key = 'hex'
class If(Func):
4180class If(Func):
4181    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'if'
class Initcap(Func):
4184class Initcap(Func):
4185    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'initcap'
class JSONKeyValue(Expression):
4188class JSONKeyValue(Expression):
4189    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'jsonkeyvalue'
class JSONObject(Func):
4192class JSONObject(Func):
4193    arg_types = {
4194        "expressions": False,
4195        "null_handling": False,
4196        "unique_keys": False,
4197        "return_type": False,
4198        "format_json": False,
4199        "encoding": False,
4200    }
arg_types = {'expressions': False, 'null_handling': False, 'unique_keys': False, 'return_type': False, 'format_json': False, 'encoding': False}
key = 'jsonobject'
class OpenJSONColumnDef(Expression):
4203class OpenJSONColumnDef(Expression):
4204    arg_types = {"this": True, "kind": True, "path": False, "as_json": False}
arg_types = {'this': True, 'kind': True, 'path': False, 'as_json': False}
key = 'openjsoncolumndef'
class OpenJSON(Func):
4207class OpenJSON(Func):
4208    arg_types = {"this": True, "path": False, "expressions": False}
arg_types = {'this': True, 'path': False, 'expressions': False}
key = 'openjson'
class JSONBContains(Binary):
4211class JSONBContains(Binary):
4212    _sql_names = ["JSONB_CONTAINS"]
key = 'jsonbcontains'
class JSONExtract(Binary, Func):
4215class JSONExtract(Binary, Func):
4216    _sql_names = ["JSON_EXTRACT"]
key = 'jsonextract'
class JSONExtractScalar(JSONExtract):
4219class JSONExtractScalar(JSONExtract):
4220    _sql_names = ["JSON_EXTRACT_SCALAR"]
key = 'jsonextractscalar'
class JSONBExtract(JSONExtract):
4223class JSONBExtract(JSONExtract):
4224    _sql_names = ["JSONB_EXTRACT"]
key = 'jsonbextract'
class JSONBExtractScalar(JSONExtract):
4227class JSONBExtractScalar(JSONExtract):
4228    _sql_names = ["JSONB_EXTRACT_SCALAR"]
key = 'jsonbextractscalar'
class JSONFormat(Func):
4231class JSONFormat(Func):
4232    arg_types = {"this": False, "options": False}
4233    _sql_names = ["JSON_FORMAT"]
arg_types = {'this': False, 'options': False}
key = 'jsonformat'
class Least(Func):
4236class Least(Func):
4237    arg_types = {"expressions": False}
4238    is_var_len_args = True
arg_types = {'expressions': False}
is_var_len_args = True
key = 'least'
class Left(Func):
4241class Left(Func):
4242    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'left'
class Length(Func):
4249class Length(Func):
4250    _sql_names = ["LENGTH", "LEN"]
key = 'length'
class Levenshtein(Func):
4253class Levenshtein(Func):
4254    arg_types = {
4255        "this": True,
4256        "expression": False,
4257        "ins_cost": False,
4258        "del_cost": False,
4259        "sub_cost": False,
4260    }
arg_types = {'this': True, 'expression': False, 'ins_cost': False, 'del_cost': False, 'sub_cost': False}
key = 'levenshtein'
class Ln(Func):
4263class Ln(Func):
4264    pass
key = 'ln'
class Log(Func):
4267class Log(Func):
4268    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'log'
class Log2(Func):
4271class Log2(Func):
4272    pass
key = 'log2'
class Log10(Func):
4275class Log10(Func):
4276    pass
key = 'log10'
class LogicalOr(AggFunc):
4279class LogicalOr(AggFunc):
4280    _sql_names = ["LOGICAL_OR", "BOOL_OR", "BOOLOR_AGG"]
key = 'logicalor'
class LogicalAnd(AggFunc):
4283class LogicalAnd(AggFunc):
4284    _sql_names = ["LOGICAL_AND", "BOOL_AND", "BOOLAND_AGG"]
key = 'logicaland'
class Lower(Func):
4287class Lower(Func):
4288    _sql_names = ["LOWER", "LCASE"]
key = 'lower'
class Map(Func):
4291class Map(Func):
4292    arg_types = {"keys": False, "values": False}
arg_types = {'keys': False, 'values': False}
key = 'map'
class StarMap(Func):
4295class StarMap(Func):
4296    pass
key = 'starmap'
class VarMap(Func):
4299class VarMap(Func):
4300    arg_types = {"keys": True, "values": True}
4301    is_var_len_args = True
4302
4303    @property
4304    def keys(self) -> t.List[Expression]:
4305        return self.args["keys"].expressions
4306
4307    @property
4308    def values(self) -> t.List[Expression]:
4309        return self.args["values"].expressions
arg_types = {'keys': True, 'values': True}
is_var_len_args = True
key = 'varmap'
class MatchAgainst(Func):
4313class MatchAgainst(Func):
4314    arg_types = {"this": True, "expressions": True, "modifier": False}
arg_types = {'this': True, 'expressions': True, 'modifier': False}
key = 'matchagainst'
class Max(AggFunc):
4317class Max(AggFunc):
4318    arg_types = {"this": True, "expressions": False}
4319    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'max'
class MD5(Func):
4322class MD5(Func):
4323    _sql_names = ["MD5"]
key = 'md5'
class Min(AggFunc):
4326class Min(AggFunc):
4327    arg_types = {"this": True, "expressions": False}
4328    is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
is_var_len_args = True
key = 'min'
class Month(Func):
4331class Month(Func):
4332    pass
key = 'month'
class Nvl2(Func):
4335class Nvl2(Func):
4336    arg_types = {"this": True, "true": True, "false": False}
arg_types = {'this': True, 'true': True, 'false': False}
key = 'nvl2'
class Posexplode(Func):
4339class Posexplode(Func):
4340    pass
key = 'posexplode'
class Pow(Binary, Func):
4343class Pow(Binary, Func):
4344    _sql_names = ["POWER", "POW"]
key = 'pow'
class PercentileCont(AggFunc):
4347class PercentileCont(AggFunc):
4348    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentilecont'
class PercentileDisc(AggFunc):
4351class PercentileDisc(AggFunc):
4352    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'percentiledisc'
class Quantile(AggFunc):
4355class Quantile(AggFunc):
4356    arg_types = {"this": True, "quantile": True}
arg_types = {'this': True, 'quantile': True}
key = 'quantile'
class ApproxQuantile(Quantile):
4359class ApproxQuantile(Quantile):
4360    arg_types = {"this": True, "quantile": True, "accuracy": False, "weight": False}
arg_types = {'this': True, 'quantile': True, 'accuracy': False, 'weight': False}
key = 'approxquantile'
class RangeN(Func):
4363class RangeN(Func):
4364    arg_types = {"this": True, "expressions": True, "each": False}
arg_types = {'this': True, 'expressions': True, 'each': False}
key = 'rangen'
class ReadCSV(Func):
4367class ReadCSV(Func):
4368    _sql_names = ["READ_CSV"]
4369    is_var_len_args = True
4370    arg_types = {"this": True, "expressions": False}
is_var_len_args = True
arg_types = {'this': True, 'expressions': False}
key = 'readcsv'
class Reduce(Func):
4373class Reduce(Func):
4374    arg_types = {"this": True, "initial": True, "merge": True, "finish": False}
arg_types = {'this': True, 'initial': True, 'merge': True, 'finish': False}
key = 'reduce'
class RegexpExtract(Func):
4377class RegexpExtract(Func):
4378    arg_types = {
4379        "this": True,
4380        "expression": True,
4381        "position": False,
4382        "occurrence": False,
4383        "group": False,
4384    }
arg_types = {'this': True, 'expression': True, 'position': False, 'occurrence': False, 'group': False}
key = 'regexpextract'
class RegexpLike(Func):
4387class RegexpLike(Func):
4388    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexplike'
class RegexpILike(Func):
4391class RegexpILike(Func):
4392    arg_types = {"this": True, "expression": True, "flag": False}
arg_types = {'this': True, 'expression': True, 'flag': False}
key = 'regexpilike'
class RegexpSplit(Func):
4397class RegexpSplit(Func):
4398    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'regexpsplit'
class Repeat(Func):
4401class Repeat(Func):
4402    arg_types = {"this": True, "times": True}
arg_types = {'this': True, 'times': True}
key = 'repeat'
class Round(Func):
4405class Round(Func):
4406    arg_types = {"this": True, "decimals": False}
arg_types = {'this': True, 'decimals': False}
key = 'round'
class RowNumber(Func):
4409class RowNumber(Func):
4410    arg_types: t.Dict[str, t.Any] = {}
arg_types: Dict[str, Any] = {}
key = 'rownumber'
class SafeDivide(Func):
4413class SafeDivide(Func):
4414    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'safedivide'
class SetAgg(AggFunc):
4417class SetAgg(AggFunc):
4418    pass
key = 'setagg'
class SHA(Func):
4421class SHA(Func):
4422    _sql_names = ["SHA", "SHA1"]
key = 'sha'
class SHA2(Func):
4425class SHA2(Func):
4426    _sql_names = ["SHA2"]
4427    arg_types = {"this": True, "length": False}
arg_types = {'this': True, 'length': False}
key = 'sha2'
class SortArray(Func):
4430class SortArray(Func):
4431    arg_types = {"this": True, "asc": False}
arg_types = {'this': True, 'asc': False}
key = 'sortarray'
class Split(Func):
4434class Split(Func):
4435    arg_types = {"this": True, "expression": True, "limit": False}
arg_types = {'this': True, 'expression': True, 'limit': False}
key = 'split'
class Substring(Func):
4440class Substring(Func):
4441    arg_types = {"this": True, "start": False, "length": False}
arg_types = {'this': True, 'start': False, 'length': False}
key = 'substring'
class StandardHash(Func):
4444class StandardHash(Func):
4445    arg_types = {"this": True, "expression": False}
arg_types = {'this': True, 'expression': False}
key = 'standardhash'
class StrPosition(Func):
4448class StrPosition(Func):
4449    arg_types = {
4450        "this": True,
4451        "substr": True,
4452        "position": False,
4453        "instance": False,
4454    }
arg_types = {'this': True, 'substr': True, 'position': False, 'instance': False}
key = 'strposition'
class StrToDate(Func):
4457class StrToDate(Func):
4458    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtodate'
class StrToTime(Func):
4461class StrToTime(Func):
4462    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'strtotime'
class StrToUnix(Func):
4467class StrToUnix(Func):
4468    arg_types = {"this": False, "format": False}
arg_types = {'this': False, 'format': False}
key = 'strtounix'
class NumberToStr(Func):
4471class NumberToStr(Func):
4472    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'numbertostr'
class FromBase(Func):
4475class FromBase(Func):
4476    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'frombase'
class Struct(Func):
4479class Struct(Func):
4480    arg_types = {"expressions": True}
4481    is_var_len_args = True
arg_types = {'expressions': True}
is_var_len_args = True
key = 'struct'
class StructExtract(Func):
4484class StructExtract(Func):
4485    arg_types = {"this": True, "expression": True}
arg_types = {'this': True, 'expression': True}
key = 'structextract'
class Sum(AggFunc):
4488class Sum(AggFunc):
4489    pass
key = 'sum'
class Sqrt(Func):
4492class Sqrt(Func):
4493    pass
key = 'sqrt'
class Stddev(AggFunc):
4496class Stddev(AggFunc):
4497    pass
key = 'stddev'
class StddevPop(AggFunc):
4500class StddevPop(AggFunc):
4501    pass
key = 'stddevpop'
class StddevSamp(AggFunc):
4504class StddevSamp(AggFunc):
4505    pass
key = 'stddevsamp'
class TimeToStr(Func):
4508class TimeToStr(Func):
4509    arg_types = {"this": True, "format": True}
arg_types = {'this': True, 'format': True}
key = 'timetostr'
class TimeToTimeStr(Func):
4512class TimeToTimeStr(Func):
4513    pass
key = 'timetotimestr'
class TimeToUnix(Func):
4516class TimeToUnix(Func):
4517    pass
key = 'timetounix'
class TimeStrToDate(Func):
4520class TimeStrToDate(Func):
4521    pass
key = 'timestrtodate'
class TimeStrToTime(Func):
4524class TimeStrToTime(Func):
4525    pass
key = 'timestrtotime'
class TimeStrToUnix(Func):
4528class TimeStrToUnix(Func):
4529    pass
key = 'timestrtounix'
class Trim(Func):
4532class Trim(Func):
4533    arg_types = {
4534        "this": True,
4535        "expression": False,
4536        "position": False,
4537        "collation": False,
4538    }
arg_types = {'this': True, 'expression': False, 'position': False, 'collation': False}
key = 'trim'
class TsOrDsAdd(Func, TimeUnit):
4541class TsOrDsAdd(Func, TimeUnit):
4542    arg_types = {"this": True, "expression": True, "unit": False}
arg_types = {'this': True, 'expression': True, 'unit': False}
key = 'tsordsadd'
class TsOrDsToDateStr(Func):
4545class TsOrDsToDateStr(Func):
4546    pass
key = 'tsordstodatestr'
class TsOrDsToDate(Func):
4549class TsOrDsToDate(Func):
4550    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'tsordstodate'
class TsOrDiToDi(Func):
4553class TsOrDiToDi(Func):
4554    pass
key = 'tsorditodi'
class Unhex(Func):
4557class Unhex(Func):
4558    pass
key = 'unhex'
class UnixToStr(Func):
4561class UnixToStr(Func):
4562    arg_types = {"this": True, "format": False}
arg_types = {'this': True, 'format': False}
key = 'unixtostr'
class UnixToTime(Func):
4567class UnixToTime(Func):
4568    arg_types = {"this": True, "scale": False, "zone": False, "hours": False, "minutes": False}
4569
4570    SECONDS = Literal.string("seconds")
4571    MILLIS = Literal.string("millis")
4572    MICROS = Literal.string("micros")
arg_types = {'this': True, 'scale': False, 'zone': False, 'hours': False, 'minutes': False}
SECONDS = (LITERAL this: seconds, is_string: True)
MILLIS = (LITERAL this: millis, is_string: True)
MICROS = (LITERAL this: micros, is_string: True)
key = 'unixtotime'
class UnixToTimeStr(Func):
4575class UnixToTimeStr(Func):
4576    pass
key = 'unixtotimestr'
class Upper(Func):
4579class Upper(Func):
4580    _sql_names = ["UPPER", "UCASE"]
key = 'upper'
class Variance(AggFunc):
4583class Variance(AggFunc):
4584    _sql_names = ["VARIANCE", "VARIANCE_SAMP", "VAR_SAMP"]
key = 'variance'
class VariancePop(AggFunc):
4587class VariancePop(AggFunc):
4588    _sql_names = ["VARIANCE_POP", "VAR_POP"]
key = 'variancepop'
class Week(Func):
4591class Week(Func):
4592    arg_types = {"this": True, "mode": False}
arg_types = {'this': True, 'mode': False}
key = 'week'
class XMLTable(Func):
4595class XMLTable(Func):
4596    arg_types = {"this": True, "passing": False, "columns": False, "by_ref": False}
arg_types = {'this': True, 'passing': False, 'columns': False, 'by_ref': False}
key = 'xmltable'
class Year(Func):
4599class Year(Func):
4600    pass
key = 'year'
class Use(Expression):
4603class Use(Expression):
4604    arg_types = {"this": True, "kind": False}
arg_types = {'this': True, 'kind': False}
key = 'use'
class Merge(Expression):
4607class Merge(Expression):
4608    arg_types = {"this": True, "using": True, "on": True, "expressions": True}
arg_types = {'this': True, 'using': True, 'on': True, 'expressions': True}
key = 'merge'
class When(Func):
4611class When(Func):
4612    arg_types = {"matched": True, "source": False, "condition": False, "then": True}
arg_types = {'matched': True, 'source': False, 'condition': False, 'then': True}
key = 'when'
class NextValueFor(Func):
4617class NextValueFor(Func):
4618    arg_types = {"this": True, "order": False}
arg_types = {'this': True, 'order': False}
key = 'nextvaluefor'
ALL_FUNCTIONS = [<class 'sqlglot.expressions.Abs'>, <class 'sqlglot.expressions.AnyValue'>, <class 'sqlglot.expressions.ApproxDistinct'>, <class 'sqlglot.expressions.ApproxQuantile'>, <class 'sqlglot.expressions.Array'>, <class 'sqlglot.expressions.ArrayAgg'>, <class 'sqlglot.expressions.ArrayAll'>, <class 'sqlglot.expressions.ArrayAny'>, <class 'sqlglot.expressions.ArrayConcat'>, <class 'sqlglot.expressions.ArrayContains'>, <class 'sqlglot.expressions.ArrayFilter'>, <class 'sqlglot.expressions.ArrayJoin'>, <class 'sqlglot.expressions.ArraySize'>, <class 'sqlglot.expressions.ArraySort'>, <class 'sqlglot.expressions.ArraySum'>, <class 'sqlglot.expressions.ArrayUnionAgg'>, <class 'sqlglot.expressions.Avg'>, <class 'sqlglot.expressions.Case'>, <class 'sqlglot.expressions.Cast'>, <class 'sqlglot.expressions.CastToStrType'>, <class 'sqlglot.expressions.Ceil'>, <class 'sqlglot.expressions.Coalesce'>, <class 'sqlglot.expressions.Concat'>, <class 'sqlglot.expressions.ConcatWs'>, <class 'sqlglot.expressions.Count'>, <class 'sqlglot.expressions.CountIf'>, <class 'sqlglot.expressions.CurrentDate'>, <class 'sqlglot.expressions.CurrentDatetime'>, <class 'sqlglot.expressions.CurrentTime'>, <class 'sqlglot.expressions.CurrentTimestamp'>, <class 'sqlglot.expressions.CurrentUser'>, <class 'sqlglot.expressions.Date'>, <class 'sqlglot.expressions.DateAdd'>, <class 'sqlglot.expressions.DateDiff'>, <class 'sqlglot.expressions.DateFromParts'>, <class 'sqlglot.expressions.DateStrToDate'>, <class 'sqlglot.expressions.DateSub'>, <class 'sqlglot.expressions.DateToDateStr'>, <class 'sqlglot.expressions.DateToDi'>, <class 'sqlglot.expressions.DateTrunc'>, <class 'sqlglot.expressions.DatetimeAdd'>, <class 'sqlglot.expressions.DatetimeDiff'>, <class 'sqlglot.expressions.DatetimeSub'>, <class 'sqlglot.expressions.DatetimeTrunc'>, <class 'sqlglot.expressions.Day'>, <class 'sqlglot.expressions.DayOfMonth'>, <class 'sqlglot.expressions.DayOfWeek'>, <class 'sqlglot.expressions.DayOfYear'>, <class 'sqlglot.expressions.Decode'>, <class 'sqlglot.expressions.DiToDate'>, <class 'sqlglot.expressions.Encode'>, <class 'sqlglot.expressions.Exp'>, <class 'sqlglot.expressions.Explode'>, <class 'sqlglot.expressions.Extract'>, <class 'sqlglot.expressions.Floor'>, <class 'sqlglot.expressions.FromBase'>, <class 'sqlglot.expressions.FromBase64'>, <class 'sqlglot.expressions.GenerateSeries'>, <class 'sqlglot.expressions.Greatest'>, <class 'sqlglot.expressions.GroupConcat'>, <class 'sqlglot.expressions.Hex'>, <class 'sqlglot.expressions.Hll'>, <class 'sqlglot.expressions.If'>, <class 'sqlglot.expressions.Initcap'>, <class 'sqlglot.expressions.JSONBExtract'>, <class 'sqlglot.expressions.JSONBExtractScalar'>, <class 'sqlglot.expressions.JSONExtract'>, <class 'sqlglot.expressions.JSONExtractScalar'>, <class 'sqlglot.expressions.JSONFormat'>, <class 'sqlglot.expressions.JSONObject'>, <class 'sqlglot.expressions.LastDateOfMonth'>, <class 'sqlglot.expressions.Least'>, <class 'sqlglot.expressions.Left'>, <class 'sqlglot.expressions.Length'>, <class 'sqlglot.expressions.Levenshtein'>, <class 'sqlglot.expressions.Ln'>, <class 'sqlglot.expressions.Log'>, <class 'sqlglot.expressions.Log10'>, <class 'sqlglot.expressions.Log2'>, <class 'sqlglot.expressions.LogicalAnd'>, <class 'sqlglot.expressions.LogicalOr'>, <class 'sqlglot.expressions.Lower'>, <class 'sqlglot.expressions.MD5'>, <class 'sqlglot.expressions.Map'>, <class 'sqlglot.expressions.MatchAgainst'>, <class 'sqlglot.expressions.Max'>, <class 'sqlglot.expressions.Min'>, <class 'sqlglot.expressions.Month'>, <class 'sqlglot.expressions.NextValueFor'>, <class 'sqlglot.expressions.NumberToStr'>, <class 'sqlglot.expressions.Nvl2'>, <class 'sqlglot.expressions.OpenJSON'>, <class 'sqlglot.expressions.ParameterizedAgg'>, <class 'sqlglot.expressions.PercentileCont'>, <class 'sqlglot.expressions.PercentileDisc'>, <class 'sqlglot.expressions.Posexplode'>, <class 'sqlglot.expressions.Pow'>, <class 'sqlglot.expressions.Quantile'>, <class 'sqlglot.expressions.RangeN'>, <class 'sqlglot.expressions.ReadCSV'>, <class 'sqlglot.expressions.Reduce'>, <class 'sqlglot.expressions.RegexpExtract'>, <class 'sqlglot.expressions.RegexpILike'>, <class 'sqlglot.expressions.RegexpLike'>, <class 'sqlglot.expressions.RegexpSplit'>, <class 'sqlglot.expressions.Repeat'>, <class 'sqlglot.expressions.Right'>, <class 'sqlglot.expressions.Round'>, <class 'sqlglot.expressions.RowNumber'>, <class 'sqlglot.expressions.SHA'>, <class 'sqlglot.expressions.SHA2'>, <class 'sqlglot.expressions.SafeConcat'>, <class 'sqlglot.expressions.SafeDivide'>, <class 'sqlglot.expressions.SetAgg'>, <class 'sqlglot.expressions.SortArray'>, <class 'sqlglot.expressions.Split'>, <class 'sqlglot.expressions.Sqrt'>, <class 'sqlglot.expressions.StandardHash'>, <class 'sqlglot.expressions.StarMap'>, <class 'sqlglot.expressions.Stddev'>, <class 'sqlglot.expressions.StddevPop'>, <class 'sqlglot.expressions.StddevSamp'>, <class 'sqlglot.expressions.StrPosition'>, <class 'sqlglot.expressions.StrToDate'>, <class 'sqlglot.expressions.StrToTime'>, <class 'sqlglot.expressions.StrToUnix'>, <class 'sqlglot.expressions.Struct'>, <class 'sqlglot.expressions.StructExtract'>, <class 'sqlglot.expressions.Substring'>, <class 'sqlglot.expressions.Sum'>, <class 'sqlglot.expressions.TimeAdd'>, <class 'sqlglot.expressions.TimeDiff'>, <class 'sqlglot.expressions.TimeStrToDate'>, <class 'sqlglot.expressions.TimeStrToTime'>, <class 'sqlglot.expressions.TimeStrToUnix'>, <class 'sqlglot.expressions.TimeSub'>, <class 'sqlglot.expressions.TimeToStr'>, <class 'sqlglot.expressions.TimeToTimeStr'>, <class 'sqlglot.expressions.TimeToUnix'>, <class 'sqlglot.expressions.TimeTrunc'>, <class 'sqlglot.expressions.TimestampAdd'>, <class 'sqlglot.expressions.TimestampDiff'>, <class 'sqlglot.expressions.TimestampSub'>, <class 'sqlglot.expressions.TimestampTrunc'>, <class 'sqlglot.expressions.ToBase64'>, <class 'sqlglot.expressions.ToChar'>, <class 'sqlglot.expressions.Trim'>, <class 'sqlglot.expressions.TryCast'>, <class 'sqlglot.expressions.TsOrDiToDi'>, <class 'sqlglot.expressions.TsOrDsAdd'>, <class 'sqlglot.expressions.TsOrDsToDate'>, <class 'sqlglot.expressions.TsOrDsToDateStr'>, <class 'sqlglot.expressions.Unhex'>, <class 'sqlglot.expressions.UnixToStr'>, <class 'sqlglot.expressions.UnixToTime'>, <class 'sqlglot.expressions.UnixToTimeStr'>, <class 'sqlglot.expressions.Upper'>, <class 'sqlglot.expressions.VarMap'>, <class 'sqlglot.expressions.Variance'>, <class 'sqlglot.expressions.VariancePop'>, <class 'sqlglot.expressions.Week'>, <class 'sqlglot.expressions.WeekOfYear'>, <class 'sqlglot.expressions.When'>, <class 'sqlglot.expressions.XMLTable'>, <class 'sqlglot.expressions.Year'>]
def maybe_parse( sql_or_expression: Union[str, sqlglot.expressions.Expression], *, into: Union[str, Type[sqlglot.expressions.Expression], Collection[Union[str, Type[sqlglot.expressions.Expression]]], NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, prefix: Optional[str] = None, copy: bool = False, **opts) -> sqlglot.expressions.Expression:
4655def maybe_parse(
4656    sql_or_expression: ExpOrStr,
4657    *,
4658    into: t.Optional[IntoType] = None,
4659    dialect: DialectType = None,
4660    prefix: t.Optional[str] = None,
4661    copy: bool = False,
4662    **opts,
4663) -> Expression:
4664    """Gracefully handle a possible string or expression.
4665
4666    Example:
4667        >>> maybe_parse("1")
4668        (LITERAL this: 1, is_string: False)
4669        >>> maybe_parse(to_identifier("x"))
4670        (IDENTIFIER this: x, quoted: False)
4671
4672    Args:
4673        sql_or_expression: the SQL code string or an expression
4674        into: the SQLGlot Expression to parse into
4675        dialect: the dialect used to parse the input expressions (in the case that an
4676            input expression is a SQL string).
4677        prefix: a string to prefix the sql with before it gets parsed
4678            (automatically includes a space)
4679        copy: whether or not to copy the expression.
4680        **opts: other options to use to parse the input expressions (again, in the case
4681            that an input expression is a SQL string).
4682
4683    Returns:
4684        Expression: the parsed or given expression.
4685    """
4686    if isinstance(sql_or_expression, Expression):
4687        if copy:
4688            return sql_or_expression.copy()
4689        return sql_or_expression
4690
4691    if sql_or_expression is None:
4692        raise ParseError(f"SQL cannot be None")
4693
4694    import sqlglot
4695
4696    sql = str(sql_or_expression)
4697    if prefix:
4698        sql = f"{prefix} {sql}"
4699
4700    return sqlglot.parse_one(sql, read=dialect, into=into, **opts)

Gracefully handle a possible string or expression.

Example:
>>> maybe_parse("1")
(LITERAL this: 1, is_string: False)
>>> maybe_parse(to_identifier("x"))
(IDENTIFIER this: x, quoted: False)
Arguments:
  • sql_or_expression: the SQL code string or an expression
  • into: the SQLGlot Expression to parse into
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • prefix: a string to prefix the sql with before it gets parsed (automatically includes a space)
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Expression: the parsed or given expression.

def union( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Union:
4884def union(
4885    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4886) -> Union:
4887    """
4888    Initializes a syntax tree from one UNION expression.
4889
4890    Example:
4891        >>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
4892        'SELECT * FROM foo UNION SELECT * FROM bla'
4893
4894    Args:
4895        left: the SQL code string corresponding to the left-hand side.
4896            If an `Expression` instance is passed, it will be used as-is.
4897        right: the SQL code string corresponding to the right-hand side.
4898            If an `Expression` instance is passed, it will be used as-is.
4899        distinct: set the DISTINCT flag if and only if this is true.
4900        dialect: the dialect used to parse the input expression.
4901        opts: other options to use to parse the input expressions.
4902
4903    Returns:
4904        The new Union instance.
4905    """
4906    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4907    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4908
4909    return Union(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one UNION expression.

Example:
>>> union("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo UNION SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Union instance.

def intersect( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Intersect:
4912def intersect(
4913    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4914) -> Intersect:
4915    """
4916    Initializes a syntax tree from one INTERSECT expression.
4917
4918    Example:
4919        >>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
4920        'SELECT * FROM foo INTERSECT SELECT * FROM bla'
4921
4922    Args:
4923        left: the SQL code string corresponding to the left-hand side.
4924            If an `Expression` instance is passed, it will be used as-is.
4925        right: the SQL code string corresponding to the right-hand side.
4926            If an `Expression` instance is passed, it will be used as-is.
4927        distinct: set the DISTINCT flag if and only if this is true.
4928        dialect: the dialect used to parse the input expression.
4929        opts: other options to use to parse the input expressions.
4930
4931    Returns:
4932        The new Intersect instance.
4933    """
4934    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4935    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4936
4937    return Intersect(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one INTERSECT expression.

Example:
>>> intersect("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo INTERSECT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Intersect instance.

def except_( left: Union[str, sqlglot.expressions.Expression], right: Union[str, sqlglot.expressions.Expression], distinct: bool = True, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Except:
4940def except_(
4941    left: ExpOrStr, right: ExpOrStr, distinct: bool = True, dialect: DialectType = None, **opts
4942) -> Except:
4943    """
4944    Initializes a syntax tree from one EXCEPT expression.
4945
4946    Example:
4947        >>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
4948        'SELECT * FROM foo EXCEPT SELECT * FROM bla'
4949
4950    Args:
4951        left: the SQL code string corresponding to the left-hand side.
4952            If an `Expression` instance is passed, it will be used as-is.
4953        right: the SQL code string corresponding to the right-hand side.
4954            If an `Expression` instance is passed, it will be used as-is.
4955        distinct: set the DISTINCT flag if and only if this is true.
4956        dialect: the dialect used to parse the input expression.
4957        opts: other options to use to parse the input expressions.
4958
4959    Returns:
4960        The new Except instance.
4961    """
4962    left = maybe_parse(sql_or_expression=left, dialect=dialect, **opts)
4963    right = maybe_parse(sql_or_expression=right, dialect=dialect, **opts)
4964
4965    return Except(this=left, expression=right, distinct=distinct)

Initializes a syntax tree from one EXCEPT expression.

Example:
>>> except_("SELECT * FROM foo", "SELECT * FROM bla").sql()
'SELECT * FROM foo EXCEPT SELECT * FROM bla'
Arguments:
  • left: the SQL code string corresponding to the left-hand side. If an Expression instance is passed, it will be used as-is.
  • right: the SQL code string corresponding to the right-hand side. If an Expression instance is passed, it will be used as-is.
  • distinct: set the DISTINCT flag if and only if this is true.
  • dialect: the dialect used to parse the input expression.
  • opts: other options to use to parse the input expressions.
Returns:

The new Except instance.

def select( *expressions: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4968def select(*expressions: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4969    """
4970    Initializes a syntax tree from one or multiple SELECT expressions.
4971
4972    Example:
4973        >>> select("col1", "col2").from_("tbl").sql()
4974        'SELECT col1, col2 FROM tbl'
4975
4976    Args:
4977        *expressions: the SQL code string to parse as the expressions of a
4978            SELECT statement. If an Expression instance is passed, this is used as-is.
4979        dialect: the dialect used to parse the input expressions (in the case that an
4980            input expression is a SQL string).
4981        **opts: other options to use to parse the input expressions (again, in the case
4982            that an input expression is a SQL string).
4983
4984    Returns:
4985        Select: the syntax tree for the SELECT statement.
4986    """
4987    return Select().select(*expressions, dialect=dialect, **opts)

Initializes a syntax tree from one or multiple SELECT expressions.

Example:
>>> select("col1", "col2").from_("tbl").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expressions: the SQL code string to parse as the expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expressions (in the case that an input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that an input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def from_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
4990def from_(expression: ExpOrStr, dialect: DialectType = None, **opts) -> Select:
4991    """
4992    Initializes a syntax tree from a FROM expression.
4993
4994    Example:
4995        >>> from_("tbl").select("col1", "col2").sql()
4996        'SELECT col1, col2 FROM tbl'
4997
4998    Args:
4999        *expression: the SQL code string to parse as the FROM expressions of a
5000            SELECT statement. If an Expression instance is passed, this is used as-is.
5001        dialect: the dialect used to parse the input expression (in the case that the
5002            input expression is a SQL string).
5003        **opts: other options to use to parse the input expressions (again, in the case
5004            that the input expression is a SQL string).
5005
5006    Returns:
5007        Select: the syntax tree for the SELECT statement.
5008    """
5009    return Select().from_(expression, dialect=dialect, **opts)

Initializes a syntax tree from a FROM expression.

Example:
>>> from_("tbl").select("col1", "col2").sql()
'SELECT col1, col2 FROM tbl'
Arguments:
  • *expression: the SQL code string to parse as the FROM expressions of a SELECT statement. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

Select: the syntax tree for the SELECT statement.

def update( table: str | sqlglot.expressions.Table, properties: dict, where: Union[str, sqlglot.expressions.Expression, NoneType] = None, from_: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Update:
5012def update(
5013    table: str | Table,
5014    properties: dict,
5015    where: t.Optional[ExpOrStr] = None,
5016    from_: t.Optional[ExpOrStr] = None,
5017    dialect: DialectType = None,
5018    **opts,
5019) -> Update:
5020    """
5021    Creates an update statement.
5022
5023    Example:
5024        >>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
5025        "UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
5026
5027    Args:
5028        *properties: dictionary of properties to set which are
5029            auto converted to sql objects eg None -> NULL
5030        where: sql conditional parsed into a WHERE statement
5031        from_: sql statement parsed into a FROM statement
5032        dialect: the dialect used to parse the input expressions.
5033        **opts: other options to use to parse the input expressions.
5034
5035    Returns:
5036        Update: the syntax tree for the UPDATE statement.
5037    """
5038    update_expr = Update(this=maybe_parse(table, into=Table, dialect=dialect))
5039    update_expr.set(
5040        "expressions",
5041        [
5042            EQ(this=maybe_parse(k, dialect=dialect, **opts), expression=convert(v))
5043            for k, v in properties.items()
5044        ],
5045    )
5046    if from_:
5047        update_expr.set(
5048            "from",
5049            maybe_parse(from_, into=From, dialect=dialect, prefix="FROM", **opts),
5050        )
5051    if isinstance(where, Condition):
5052        where = Where(this=where)
5053    if where:
5054        update_expr.set(
5055            "where",
5056            maybe_parse(where, into=Where, dialect=dialect, prefix="WHERE", **opts),
5057        )
5058    return update_expr

Creates an update statement.

Example:
>>> update("my_table", {"x": 1, "y": "2", "z": None}, from_="baz", where="id > 1").sql()
"UPDATE my_table SET x = 1, y = '2', z = NULL FROM baz WHERE id > 1"
Arguments:
  • *properties: dictionary of properties to set which are auto converted to sql objects eg None -> NULL
  • where: sql conditional parsed into a WHERE statement
  • from_: sql statement parsed into a FROM statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Update: the syntax tree for the UPDATE statement.

def delete( table: Union[str, sqlglot.expressions.Expression], where: Union[str, sqlglot.expressions.Expression, NoneType] = None, returning: Union[str, sqlglot.expressions.Expression, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Delete:
5061def delete(
5062    table: ExpOrStr,
5063    where: t.Optional[ExpOrStr] = None,
5064    returning: t.Optional[ExpOrStr] = None,
5065    dialect: DialectType = None,
5066    **opts,
5067) -> Delete:
5068    """
5069    Builds a delete statement.
5070
5071    Example:
5072        >>> delete("my_table", where="id > 1").sql()
5073        'DELETE FROM my_table WHERE id > 1'
5074
5075    Args:
5076        where: sql conditional parsed into a WHERE statement
5077        returning: sql conditional parsed into a RETURNING statement
5078        dialect: the dialect used to parse the input expressions.
5079        **opts: other options to use to parse the input expressions.
5080
5081    Returns:
5082        Delete: the syntax tree for the DELETE statement.
5083    """
5084    delete_expr = Delete().delete(table, dialect=dialect, copy=False, **opts)
5085    if where:
5086        delete_expr = delete_expr.where(where, dialect=dialect, copy=False, **opts)
5087    if returning:
5088        delete_expr = delete_expr.returning(returning, dialect=dialect, copy=False, **opts)
5089    return delete_expr

Builds a delete statement.

Example:
>>> delete("my_table", where="id > 1").sql()
'DELETE FROM my_table WHERE id > 1'
Arguments:
  • where: sql conditional parsed into a WHERE statement
  • returning: sql conditional parsed into a RETURNING statement
  • dialect: the dialect used to parse the input expressions.
  • **opts: other options to use to parse the input expressions.
Returns:

Delete: the syntax tree for the DELETE statement.

def insert( expression: Union[str, sqlglot.expressions.Expression], into: Union[str, sqlglot.expressions.Expression], columns: Optional[Sequence[Union[str, sqlglot.expressions.Expression]]] = None, overwrite: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Insert:
5092def insert(
5093    expression: ExpOrStr,
5094    into: ExpOrStr,
5095    columns: t.Optional[t.Sequence[ExpOrStr]] = None,
5096    overwrite: t.Optional[bool] = None,
5097    dialect: DialectType = None,
5098    copy: bool = True,
5099    **opts,
5100) -> Insert:
5101    """
5102    Builds an INSERT statement.
5103
5104    Example:
5105        >>> insert("VALUES (1, 2, 3)", "tbl").sql()
5106        'INSERT INTO tbl VALUES (1, 2, 3)'
5107
5108    Args:
5109        expression: the sql string or expression of the INSERT statement
5110        into: the tbl to insert data to.
5111        columns: optionally the table's column names.
5112        overwrite: whether to INSERT OVERWRITE or not.
5113        dialect: the dialect used to parse the input expressions.
5114        copy: whether or not to copy the expression.
5115        **opts: other options to use to parse the input expressions.
5116
5117    Returns:
5118        Insert: the syntax tree for the INSERT statement.
5119    """
5120    expr = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5121    this: Table | Schema = maybe_parse(into, into=Table, dialect=dialect, copy=copy, **opts)
5122
5123    if columns:
5124        this = _apply_list_builder(
5125            *columns,
5126            instance=Schema(this=this),
5127            arg="expressions",
5128            into=Identifier,
5129            copy=False,
5130            dialect=dialect,
5131            **opts,
5132        )
5133
5134    return Insert(this=this, expression=expr, overwrite=overwrite)

Builds an INSERT statement.

Example:
>>> insert("VALUES (1, 2, 3)", "tbl").sql()
'INSERT INTO tbl VALUES (1, 2, 3)'
Arguments:
  • expression: the sql string or expression of the INSERT statement
  • into: the tbl to insert data to.
  • columns: optionally the table's column names.
  • overwrite: whether to INSERT OVERWRITE or not.
  • dialect: the dialect used to parse the input expressions.
  • copy: whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Insert: the syntax tree for the INSERT statement.

def condition( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5137def condition(
5138    expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts
5139) -> Condition:
5140    """
5141    Initialize a logical condition expression.
5142
5143    Example:
5144        >>> condition("x=1").sql()
5145        'x = 1'
5146
5147        This is helpful for composing larger logical syntax trees:
5148        >>> where = condition("x=1")
5149        >>> where = where.and_("y=1")
5150        >>> Select().from_("tbl").select("*").where(where).sql()
5151        'SELECT * FROM tbl WHERE x = 1 AND y = 1'
5152
5153    Args:
5154        *expression: the SQL code string to parse.
5155            If an Expression instance is passed, this is used as-is.
5156        dialect: the dialect used to parse the input expression (in the case that the
5157            input expression is a SQL string).
5158        copy: Whether or not to copy `expression` (only applies to expressions).
5159        **opts: other options to use to parse the input expressions (again, in the case
5160            that the input expression is a SQL string).
5161
5162    Returns:
5163        The new Condition instance
5164    """
5165    return maybe_parse(
5166        expression,
5167        into=Condition,
5168        dialect=dialect,
5169        copy=copy,
5170        **opts,
5171    )

Initialize a logical condition expression.

Example:
>>> condition("x=1").sql()
'x = 1'

This is helpful for composing larger logical syntax trees:

>>> where = condition("x=1")
>>> where = where.and_("y=1")
>>> Select().from_("tbl").select("*").where(where).sql()
'SELECT * FROM tbl WHERE x = 1 AND y = 1'
Arguments:
  • *expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression (in the case that the input expression is a SQL string).
  • copy: Whether or not to copy expression (only applies to expressions).
  • **opts: other options to use to parse the input expressions (again, in the case that the input expression is a SQL string).
Returns:

The new Condition instance

def and_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5174def and_(
5175    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5176) -> Condition:
5177    """
5178    Combine multiple conditions with an AND logical operator.
5179
5180    Example:
5181        >>> and_("x=1", and_("y=1", "z=1")).sql()
5182        'x = 1 AND (y = 1 AND z = 1)'
5183
5184    Args:
5185        *expressions: the SQL code strings to parse.
5186            If an Expression instance is passed, this is used as-is.
5187        dialect: the dialect used to parse the input expression.
5188        copy: whether or not to copy `expressions` (only applies to Expressions).
5189        **opts: other options to use to parse the input expressions.
5190
5191    Returns:
5192        And: the new condition
5193    """
5194    return t.cast(Condition, _combine(expressions, And, dialect, copy=copy, **opts))

Combine multiple conditions with an AND logical operator.

Example:
>>> and_("x=1", and_("y=1", "z=1")).sql()
'x = 1 AND (y = 1 AND z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

And: the new condition

def or_( *expressions: Union[str, sqlglot.expressions.Expression, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Condition:
5197def or_(
5198    *expressions: t.Optional[ExpOrStr], dialect: DialectType = None, copy: bool = True, **opts
5199) -> Condition:
5200    """
5201    Combine multiple conditions with an OR logical operator.
5202
5203    Example:
5204        >>> or_("x=1", or_("y=1", "z=1")).sql()
5205        'x = 1 OR (y = 1 OR z = 1)'
5206
5207    Args:
5208        *expressions: the SQL code strings to parse.
5209            If an Expression instance is passed, this is used as-is.
5210        dialect: the dialect used to parse the input expression.
5211        copy: whether or not to copy `expressions` (only applies to Expressions).
5212        **opts: other options to use to parse the input expressions.
5213
5214    Returns:
5215        Or: the new condition
5216    """
5217    return t.cast(Condition, _combine(expressions, Or, dialect, copy=copy, **opts))

Combine multiple conditions with an OR logical operator.

Example:
>>> or_("x=1", or_("y=1", "z=1")).sql()
'x = 1 OR (y = 1 OR z = 1)'
Arguments:
  • *expressions: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether or not to copy expressions (only applies to Expressions).
  • **opts: other options to use to parse the input expressions.
Returns:

Or: the new condition

def not_( expression: Union[str, sqlglot.expressions.Expression], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts) -> sqlglot.expressions.Not:
5220def not_(expression: ExpOrStr, dialect: DialectType = None, copy: bool = True, **opts) -> Not:
5221    """
5222    Wrap a condition with a NOT operator.
5223
5224    Example:
5225        >>> not_("this_suit='black'").sql()
5226        "NOT this_suit = 'black'"
5227
5228    Args:
5229        expression: the SQL code string to parse.
5230            If an Expression instance is passed, this is used as-is.
5231        dialect: the dialect used to parse the input expression.
5232        copy: whether to copy the expression or not.
5233        **opts: other options to use to parse the input expressions.
5234
5235    Returns:
5236        The new condition.
5237    """
5238    this = condition(
5239        expression,
5240        dialect=dialect,
5241        copy=copy,
5242        **opts,
5243    )
5244    return Not(this=_wrap(this, Connector))

Wrap a condition with a NOT operator.

Example:
>>> not_("this_suit='black'").sql()
"NOT this_suit = 'black'"
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • dialect: the dialect used to parse the input expression.
  • copy: whether to copy the expression or not.
  • **opts: other options to use to parse the input expressions.
Returns:

The new condition.

def paren( expression: Union[str, sqlglot.expressions.Expression], copy: bool = True) -> sqlglot.expressions.Paren:
5247def paren(expression: ExpOrStr, copy: bool = True) -> Paren:
5248    """
5249    Wrap an expression in parentheses.
5250
5251    Example:
5252        >>> paren("5 + 3").sql()
5253        '(5 + 3)'
5254
5255    Args:
5256        expression: the SQL code string to parse.
5257            If an Expression instance is passed, this is used as-is.
5258        copy: whether to copy the expression or not.
5259
5260    Returns:
5261        The wrapped expression.
5262    """
5263    return Paren(this=maybe_parse(expression, copy=copy))

Wrap an expression in parentheses.

Example:
>>> paren("5 + 3").sql()
'(5 + 3)'
Arguments:
  • expression: the SQL code string to parse. If an Expression instance is passed, this is used as-is.
  • copy: whether to copy the expression or not.
Returns:

The wrapped expression.

SAFE_IDENTIFIER_RE = re.compile('^[_a-zA-Z][\\w]*$')
def to_identifier(name, quoted=None, copy=True):
5281def to_identifier(name, quoted=None, copy=True):
5282    """Builds an identifier.
5283
5284    Args:
5285        name: The name to turn into an identifier.
5286        quoted: Whether or not force quote the identifier.
5287        copy: Whether or not to copy a passed in Identefier node.
5288
5289    Returns:
5290        The identifier ast node.
5291    """
5292
5293    if name is None:
5294        return None
5295
5296    if isinstance(name, Identifier):
5297        identifier = _maybe_copy(name, copy)
5298    elif isinstance(name, str):
5299        identifier = Identifier(
5300            this=name,
5301            quoted=not SAFE_IDENTIFIER_RE.match(name) if quoted is None else quoted,
5302        )
5303    else:
5304        raise ValueError(f"Name needs to be a string or an Identifier, got: {name.__class__}")
5305    return identifier

Builds an identifier.

Arguments:
  • name: The name to turn into an identifier.
  • quoted: Whether or not force quote the identifier.
  • copy: Whether or not to copy a passed in Identefier node.
Returns:

The identifier ast node.

INTERVAL_STRING_RE = re.compile('\\s*([0-9]+)\\s*([a-zA-Z]+)\\s*')
def to_interval( interval: str | sqlglot.expressions.Literal) -> sqlglot.expressions.Interval:
5311def to_interval(interval: str | Literal) -> Interval:
5312    """Builds an interval expression from a string like '1 day' or '5 months'."""
5313    if isinstance(interval, Literal):
5314        if not interval.is_string:
5315            raise ValueError("Invalid interval string.")
5316
5317        interval = interval.this
5318
5319    interval_parts = INTERVAL_STRING_RE.match(interval)  # type: ignore
5320
5321    if not interval_parts:
5322        raise ValueError("Invalid interval string.")
5323
5324    return Interval(
5325        this=Literal.string(interval_parts.group(1)),
5326        unit=Var(this=interval_parts.group(2)),
5327    )

Builds an interval expression from a string like '1 day' or '5 months'.

def to_table( sql_path: Union[str, sqlglot.expressions.Table, NoneType], dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> Optional[sqlglot.expressions.Table]:
5340def to_table(
5341    sql_path: t.Optional[str | Table], dialect: DialectType = None, **kwargs
5342) -> t.Optional[Table]:
5343    """
5344    Create a table expression from a `[catalog].[schema].[table]` sql path. Catalog and schema are optional.
5345    If a table is passed in then that table is returned.
5346
5347    Args:
5348        sql_path: a `[catalog].[schema].[table]` string.
5349        dialect: the source dialect according to which the table name will be parsed.
5350        kwargs: the kwargs to instantiate the resulting `Table` expression with.
5351
5352    Returns:
5353        A table expression.
5354    """
5355    if sql_path is None or isinstance(sql_path, Table):
5356        return sql_path
5357    if not isinstance(sql_path, str):
5358        raise ValueError(f"Invalid type provided for a table: {type(sql_path)}")
5359
5360    table = maybe_parse(sql_path, into=Table, dialect=dialect)
5361    if table:
5362        for k, v in kwargs.items():
5363            table.set(k, v)
5364
5365    return table

Create a table expression from a [catalog].[schema].[table] sql path. Catalog and schema are optional. If a table is passed in then that table is returned.

Arguments:
  • sql_path: a [catalog].[schema].[table] string.
  • dialect: the source dialect according to which the table name will be parsed.
  • kwargs: the kwargs to instantiate the resulting Table expression with.
Returns:

A table expression.

def to_column( sql_path: str | sqlglot.expressions.Column, **kwargs) -> sqlglot.expressions.Column:
5368def to_column(sql_path: str | Column, **kwargs) -> Column:
5369    """
5370    Create a column from a `[table].[column]` sql path. Schema is optional.
5371
5372    If a column is passed in then that column is returned.
5373
5374    Args:
5375        sql_path: `[table].[column]` string
5376    Returns:
5377        Table: A column expression
5378    """
5379    if sql_path is None or isinstance(sql_path, Column):
5380        return sql_path
5381    if not isinstance(sql_path, str):
5382        raise ValueError(f"Invalid type provided for column: {type(sql_path)}")
5383    return column(*reversed(sql_path.split(".")), **kwargs)  # type: ignore

Create a column from a [table].[column] sql path. Schema is optional.

If a column is passed in then that column is returned.

Arguments:
  • sql_path: [table].[column] string
Returns:

Table: A column expression

def alias_( expression: Union[str, sqlglot.expressions.Expression], alias: str | sqlglot.expressions.Identifier, table: Union[bool, Sequence[str | sqlglot.expressions.Identifier]] = False, quoted: Optional[bool] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, copy: bool = True, **opts):
5386def alias_(
5387    expression: ExpOrStr,
5388    alias: str | Identifier,
5389    table: bool | t.Sequence[str | Identifier] = False,
5390    quoted: t.Optional[bool] = None,
5391    dialect: DialectType = None,
5392    copy: bool = True,
5393    **opts,
5394):
5395    """Create an Alias expression.
5396
5397    Example:
5398        >>> alias_('foo', 'bar').sql()
5399        'foo AS bar'
5400
5401        >>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
5402        '(SELECT 1, 2) AS bar(a, b)'
5403
5404    Args:
5405        expression: the SQL code strings to parse.
5406            If an Expression instance is passed, this is used as-is.
5407        alias: the alias name to use. If the name has
5408            special characters it is quoted.
5409        table: Whether or not to create a table alias, can also be a list of columns.
5410        quoted: whether or not to quote the alias
5411        dialect: the dialect used to parse the input expression.
5412        copy: Whether or not to copy the expression.
5413        **opts: other options to use to parse the input expressions.
5414
5415    Returns:
5416        Alias: the aliased expression
5417    """
5418    exp = maybe_parse(expression, dialect=dialect, copy=copy, **opts)
5419    alias = to_identifier(alias, quoted=quoted)
5420
5421    if table:
5422        table_alias = TableAlias(this=alias)
5423        exp.set("alias", table_alias)
5424
5425        if not isinstance(table, bool):
5426            for column in table:
5427                table_alias.append("columns", to_identifier(column, quoted=quoted))
5428
5429        return exp
5430
5431    # We don't set the "alias" arg for Window expressions, because that would add an IDENTIFIER node in
5432    # the AST, representing a "named_window" [1] construct (eg. bigquery). What we want is an ALIAS node
5433    # for the complete Window expression.
5434    #
5435    # [1]: https://cloud.google.com/bigquery/docs/reference/standard-sql/window-function-calls
5436
5437    if "alias" in exp.arg_types and not isinstance(exp, Window):
5438        exp.set("alias", alias)
5439        return exp
5440    return Alias(this=exp, alias=alias)

Create an Alias expression.

Example:
>>> alias_('foo', 'bar').sql()
'foo AS bar'
>>> alias_('(select 1, 2)', 'bar', table=['a', 'b']).sql()
'(SELECT 1, 2) AS bar(a, b)'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use. If the name has special characters it is quoted.
  • table: Whether or not to create a table alias, can also be a list of columns.
  • quoted: whether or not to quote the alias
  • dialect: the dialect used to parse the input expression.
  • copy: Whether or not to copy the expression.
  • **opts: other options to use to parse the input expressions.
Returns:

Alias: the aliased expression

def subquery( expression: Union[str, sqlglot.expressions.Expression], alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **opts) -> sqlglot.expressions.Select:
5443def subquery(
5444    expression: ExpOrStr,
5445    alias: t.Optional[Identifier | str] = None,
5446    dialect: DialectType = None,
5447    **opts,
5448) -> Select:
5449    """
5450    Build a subquery expression.
5451
5452    Example:
5453        >>> subquery('select x from tbl', 'bar').select('x').sql()
5454        'SELECT x FROM (SELECT x FROM tbl) AS bar'
5455
5456    Args:
5457        expression: the SQL code strings to parse.
5458            If an Expression instance is passed, this is used as-is.
5459        alias: the alias name to use.
5460        dialect: the dialect used to parse the input expression.
5461        **opts: other options to use to parse the input expressions.
5462
5463    Returns:
5464        A new Select instance with the subquery expression included.
5465    """
5466
5467    expression = maybe_parse(expression, dialect=dialect, **opts).subquery(alias)
5468    return Select().from_(expression, dialect=dialect, **opts)

Build a subquery expression.

Example:
>>> subquery('select x from tbl', 'bar').select('x').sql()
'SELECT x FROM (SELECT x FROM tbl) AS bar'
Arguments:
  • expression: the SQL code strings to parse. If an Expression instance is passed, this is used as-is.
  • alias: the alias name to use.
  • dialect: the dialect used to parse the input expression.
  • **opts: other options to use to parse the input expressions.
Returns:

A new Select instance with the subquery expression included.

def column( col: str | sqlglot.expressions.Identifier, table: Union[sqlglot.expressions.Identifier, str, NoneType] = None, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None) -> sqlglot.expressions.Column:
5471def column(
5472    col: str | Identifier,
5473    table: t.Optional[str | Identifier] = None,
5474    db: t.Optional[str | Identifier] = None,
5475    catalog: t.Optional[str | Identifier] = None,
5476    quoted: t.Optional[bool] = None,
5477) -> Column:
5478    """
5479    Build a Column.
5480
5481    Args:
5482        col: Column name.
5483        table: Table name.
5484        db: Database name.
5485        catalog: Catalog name.
5486        quoted: Whether to force quotes on the column's identifiers.
5487
5488    Returns:
5489        The new Column instance.
5490    """
5491    return Column(
5492        this=to_identifier(col, quoted=quoted),
5493        table=to_identifier(table, quoted=quoted),
5494        db=to_identifier(db, quoted=quoted),
5495        catalog=to_identifier(catalog, quoted=quoted),
5496    )

Build a Column.

Arguments:
  • col: Column name.
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quoted: Whether to force quotes on the column's identifiers.
Returns:

The new Column instance.

def cast( expression: Union[str, sqlglot.expressions.Expression], to: str | sqlglot.expressions.DataType | sqlglot.expressions.DataType.Type, **opts) -> sqlglot.expressions.Cast:
5499def cast(expression: ExpOrStr, to: str | DataType | DataType.Type, **opts) -> Cast:
5500    """Cast an expression to a data type.
5501
5502    Example:
5503        >>> cast('x + 1', 'int').sql()
5504        'CAST(x + 1 AS INT)'
5505
5506    Args:
5507        expression: The expression to cast.
5508        to: The datatype to cast to.
5509
5510    Returns:
5511        The new Cast instance.
5512    """
5513    expression = maybe_parse(expression, **opts)
5514    return Cast(this=expression, to=DataType.build(to, **opts))

Cast an expression to a data type.

Example:
>>> cast('x + 1', 'int').sql()
'CAST(x + 1 AS INT)'
Arguments:
  • expression: The expression to cast.
  • to: The datatype to cast to.
Returns:

The new Cast instance.

def table_( table: sqlglot.expressions.Identifier | str, db: Union[sqlglot.expressions.Identifier, str, NoneType] = None, catalog: Union[sqlglot.expressions.Identifier, str, NoneType] = None, quoted: Optional[bool] = None, alias: Union[sqlglot.expressions.Identifier, str, NoneType] = None) -> sqlglot.expressions.Table:
5517def table_(
5518    table: Identifier | str,
5519    db: t.Optional[Identifier | str] = None,
5520    catalog: t.Optional[Identifier | str] = None,
5521    quoted: t.Optional[bool] = None,
5522    alias: t.Optional[Identifier | str] = None,
5523) -> Table:
5524    """Build a Table.
5525
5526    Args:
5527        table: Table name.
5528        db: Database name.
5529        catalog: Catalog name.
5530        quote: Whether to force quotes on the table's identifiers.
5531        alias: Table's alias.
5532
5533    Returns:
5534        The new Table instance.
5535    """
5536    return Table(
5537        this=to_identifier(table, quoted=quoted),
5538        db=to_identifier(db, quoted=quoted),
5539        catalog=to_identifier(catalog, quoted=quoted),
5540        alias=TableAlias(this=to_identifier(alias)) if alias else None,
5541    )

Build a Table.

Arguments:
  • table: Table name.
  • db: Database name.
  • catalog: Catalog name.
  • quote: Whether to force quotes on the table's identifiers.
  • alias: Table's alias.
Returns:

The new Table instance.

def values( values: Iterable[Tuple[Any, ...]], alias: Optional[str] = None, columns: Union[Iterable[str], Dict[str, sqlglot.expressions.DataType], NoneType] = None) -> sqlglot.expressions.Values:
5544def values(
5545    values: t.Iterable[t.Tuple[t.Any, ...]],
5546    alias: t.Optional[str] = None,
5547    columns: t.Optional[t.Iterable[str] | t.Dict[str, DataType]] = None,
5548) -> Values:
5549    """Build VALUES statement.
5550
5551    Example:
5552        >>> values([(1, '2')]).sql()
5553        "VALUES (1, '2')"
5554
5555    Args:
5556        values: values statements that will be converted to SQL
5557        alias: optional alias
5558        columns: Optional list of ordered column names or ordered dictionary of column names to types.
5559         If either are provided then an alias is also required.
5560
5561    Returns:
5562        Values: the Values expression object
5563    """
5564    if columns and not alias:
5565        raise ValueError("Alias is required when providing columns")
5566
5567    return Values(
5568        expressions=[convert(tup) for tup in values],
5569        alias=(
5570            TableAlias(this=to_identifier(alias), columns=[to_identifier(x) for x in columns])
5571            if columns
5572            else (TableAlias(this=to_identifier(alias)) if alias else None)
5573        ),
5574    )

Build VALUES statement.

Example:
>>> values([(1, '2')]).sql()
"VALUES (1, '2')"
Arguments:
  • values: values statements that will be converted to SQL
  • alias: optional alias
  • columns: Optional list of ordered column names or ordered dictionary of column names to types. If either are provided then an alias is also required.
Returns:

Values: the Values expression object

def var( name: Union[str, sqlglot.expressions.Expression, NoneType]) -> sqlglot.expressions.Var:
5577def var(name: t.Optional[ExpOrStr]) -> Var:
5578    """Build a SQL variable.
5579
5580    Example:
5581        >>> repr(var('x'))
5582        '(VAR this: x)'
5583
5584        >>> repr(var(column('x', table='y')))
5585        '(VAR this: x)'
5586
5587    Args:
5588        name: The name of the var or an expression who's name will become the var.
5589
5590    Returns:
5591        The new variable node.
5592    """
5593    if not name:
5594        raise ValueError("Cannot convert empty name into var.")
5595
5596    if isinstance(name, Expression):
5597        name = name.name
5598    return Var(this=name)

Build a SQL variable.

Example:
>>> repr(var('x'))
'(VAR this: x)'
>>> repr(var(column('x', table='y')))
'(VAR this: x)'
Arguments:
  • name: The name of the var or an expression who's name will become the var.
Returns:

The new variable node.

def rename_table( old_name: str | sqlglot.expressions.Table, new_name: str | sqlglot.expressions.Table) -> sqlglot.expressions.AlterTable:
5601def rename_table(old_name: str | Table, new_name: str | Table) -> AlterTable:
5602    """Build ALTER TABLE... RENAME... expression
5603
5604    Args:
5605        old_name: The old name of the table
5606        new_name: The new name of the table
5607
5608    Returns:
5609        Alter table expression
5610    """
5611    old_table = to_table(old_name)
5612    new_table = to_table(new_name)
5613    return AlterTable(
5614        this=old_table,
5615        actions=[
5616            RenameTable(this=new_table),
5617        ],
5618    )

Build ALTER TABLE... RENAME... expression

Arguments:
  • old_name: The old name of the table
  • new_name: The new name of the table
Returns:

Alter table expression

def convert(value: Any, copy: bool = False) -> sqlglot.expressions.Expression:
5621def convert(value: t.Any, copy: bool = False) -> Expression:
5622    """Convert a python value into an expression object.
5623
5624    Raises an error if a conversion is not possible.
5625
5626    Args:
5627        value: A python object.
5628        copy: Whether or not to copy `value` (only applies to Expressions and collections).
5629
5630    Returns:
5631        Expression: the equivalent expression object.
5632    """
5633    if isinstance(value, Expression):
5634        return _maybe_copy(value, copy)
5635    if isinstance(value, str):
5636        return Literal.string(value)
5637    if isinstance(value, bool):
5638        return Boolean(this=value)
5639    if value is None or (isinstance(value, float) and math.isnan(value)):
5640        return NULL
5641    if isinstance(value, numbers.Number):
5642        return Literal.number(value)
5643    if isinstance(value, datetime.datetime):
5644        datetime_literal = Literal.string(
5645            (value if value.tzinfo else value.replace(tzinfo=datetime.timezone.utc)).isoformat()
5646        )
5647        return TimeStrToTime(this=datetime_literal)
5648    if isinstance(value, datetime.date):
5649        date_literal = Literal.string(value.strftime("%Y-%m-%d"))
5650        return DateStrToDate(this=date_literal)
5651    if isinstance(value, tuple):
5652        return Tuple(expressions=[convert(v, copy=copy) for v in value])
5653    if isinstance(value, list):
5654        return Array(expressions=[convert(v, copy=copy) for v in value])
5655    if isinstance(value, dict):
5656        return Map(
5657            keys=[convert(k, copy=copy) for k in value],
5658            values=[convert(v, copy=copy) for v in value.values()],
5659        )
5660    raise ValueError(f"Cannot convert {value}")

Convert a python value into an expression object.

Raises an error if a conversion is not possible.

Arguments:
  • value: A python object.
  • copy: Whether or not to copy value (only applies to Expressions and collections).
Returns:

Expression: the equivalent expression object.

def replace_children( expression: sqlglot.expressions.Expression, fun: Callable, *args, **kwargs) -> None:
5663def replace_children(expression: Expression, fun: t.Callable, *args, **kwargs) -> None:
5664    """
5665    Replace children of an expression with the result of a lambda fun(child) -> exp.
5666    """
5667    for k, v in expression.args.items():
5668        is_list_arg = type(v) is list
5669
5670        child_nodes = v if is_list_arg else [v]
5671        new_child_nodes = []
5672
5673        for cn in child_nodes:
5674            if isinstance(cn, Expression):
5675                for child_node in ensure_collection(fun(cn, *args, **kwargs)):
5676                    new_child_nodes.append(child_node)
5677                    child_node.parent = expression
5678                    child_node.arg_key = k
5679            else:
5680                new_child_nodes.append(cn)
5681
5682        expression.args[k] = new_child_nodes if is_list_arg else seq_get(new_child_nodes, 0)

Replace children of an expression with the result of a lambda fun(child) -> exp.

def column_table_names( expression: sqlglot.expressions.Expression, exclude: str = '') -> Set[str]:
5685def column_table_names(expression: Expression, exclude: str = "") -> t.Set[str]:
5686    """
5687    Return all table names referenced through columns in an expression.
5688
5689    Example:
5690        >>> import sqlglot
5691        >>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
5692        ['a', 'c']
5693
5694    Args:
5695        expression: expression to find table names.
5696        exclude: a table name to exclude
5697
5698    Returns:
5699        A list of unique names.
5700    """
5701    return {
5702        table
5703        for table in (column.table for column in expression.find_all(Column))
5704        if table and table != exclude
5705    }

Return all table names referenced through columns in an expression.

Example:
>>> import sqlglot
>>> sorted(column_table_names(sqlglot.parse_one("a.b AND c.d AND c.e")))
['a', 'c']
Arguments:
  • expression: expression to find table names.
  • exclude: a table name to exclude
Returns:

A list of unique names.

def table_name(table: sqlglot.expressions.Table | str) -> str:
5708def table_name(table: Table | str) -> str:
5709    """Get the full name of a table as a string.
5710
5711    Args:
5712        table: table expression node or string.
5713
5714    Examples:
5715        >>> from sqlglot import exp, parse_one
5716        >>> table_name(parse_one("select * from a.b.c").find(exp.Table))
5717        'a.b.c'
5718
5719    Returns:
5720        The table name.
5721    """
5722
5723    table = maybe_parse(table, into=Table)
5724
5725    if not table:
5726        raise ValueError(f"Cannot parse {table}")
5727
5728    return ".".join(part for part in (table.text("catalog"), table.text("db"), table.name) if part)

Get the full name of a table as a string.

Arguments:
  • table: table expression node or string.
Examples:
>>> from sqlglot import exp, parse_one
>>> table_name(parse_one("select * from a.b.c").find(exp.Table))
'a.b.c'
Returns:

The table name.

def replace_tables(expression: ~E, mapping: Dict[str, str], copy: bool = True) -> ~E:
5731def replace_tables(expression: E, mapping: t.Dict[str, str], copy: bool = True) -> E:
5732    """Replace all tables in expression according to the mapping.
5733
5734    Args:
5735        expression: expression node to be transformed and replaced.
5736        mapping: mapping of table names.
5737        copy: whether or not to copy the expression.
5738
5739    Examples:
5740        >>> from sqlglot import exp, parse_one
5741        >>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
5742        'SELECT * FROM c'
5743
5744    Returns:
5745        The mapped expression.
5746    """
5747
5748    def _replace_tables(node: Expression) -> Expression:
5749        if isinstance(node, Table):
5750            new_name = mapping.get(table_name(node))
5751            if new_name:
5752                return to_table(
5753                    new_name,
5754                    **{k: v for k, v in node.args.items() if k not in ("this", "db", "catalog")},
5755                )
5756        return node
5757
5758    return expression.transform(_replace_tables, copy=copy)

Replace all tables in expression according to the mapping.

Arguments:
  • expression: expression node to be transformed and replaced.
  • mapping: mapping of table names.
  • copy: whether or not to copy the expression.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_tables(parse_one("select * from a.b"), {"a.b": "c"}).sql()
'SELECT * FROM c'
Returns:

The mapped expression.

def replace_placeholders( expression: sqlglot.expressions.Expression, *args, **kwargs) -> sqlglot.expressions.Expression:
5761def replace_placeholders(expression: Expression, *args, **kwargs) -> Expression:
5762    """Replace placeholders in an expression.
5763
5764    Args:
5765        expression: expression node to be transformed and replaced.
5766        args: positional names that will substitute unnamed placeholders in the given order.
5767        kwargs: keyword arguments that will substitute named placeholders.
5768
5769    Examples:
5770        >>> from sqlglot import exp, parse_one
5771        >>> replace_placeholders(
5772        ...     parse_one("select * from :tbl where ? = ?"),
5773        ...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
5774        ... ).sql()
5775        "SELECT * FROM foo WHERE str_col = 'b'"
5776
5777    Returns:
5778        The mapped expression.
5779    """
5780
5781    def _replace_placeholders(node: Expression, args, **kwargs) -> Expression:
5782        if isinstance(node, Placeholder):
5783            if node.name:
5784                new_name = kwargs.get(node.name)
5785                if new_name:
5786                    return convert(new_name)
5787            else:
5788                try:
5789                    return convert(next(args))
5790                except StopIteration:
5791                    pass
5792        return node
5793
5794    return expression.transform(_replace_placeholders, iter(args), **kwargs)

Replace placeholders in an expression.

Arguments:
  • expression: expression node to be transformed and replaced.
  • args: positional names that will substitute unnamed placeholders in the given order.
  • kwargs: keyword arguments that will substitute named placeholders.
Examples:
>>> from sqlglot import exp, parse_one
>>> replace_placeholders(
...     parse_one("select * from :tbl where ? = ?"),
...     exp.to_identifier("str_col"), "b", tbl=exp.to_identifier("foo")
... ).sql()
"SELECT * FROM foo WHERE str_col = 'b'"
Returns:

The mapped expression.

def expand( expression: sqlglot.expressions.Expression, sources: Dict[str, sqlglot.expressions.Subqueryable], copy: bool = True) -> sqlglot.expressions.Expression:
5797def expand(
5798    expression: Expression, sources: t.Dict[str, Subqueryable], copy: bool = True
5799) -> Expression:
5800    """Transforms an expression by expanding all referenced sources into subqueries.
5801
5802    Examples:
5803        >>> from sqlglot import parse_one
5804        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
5805        'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
5806
5807        >>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
5808        'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
5809
5810    Args:
5811        expression: The expression to expand.
5812        sources: A dictionary of name to Subqueryables.
5813        copy: Whether or not to copy the expression during transformation. Defaults to True.
5814
5815    Returns:
5816        The transformed expression.
5817    """
5818
5819    def _expand(node: Expression):
5820        if isinstance(node, Table):
5821            name = table_name(node)
5822            source = sources.get(name)
5823            if source:
5824                subquery = source.subquery(node.alias or name)
5825                subquery.comments = [f"source: {name}"]
5826                return subquery.transform(_expand, copy=False)
5827        return node
5828
5829    return expression.transform(_expand, copy=copy)

Transforms an expression by expanding all referenced sources into subqueries.

Examples:
>>> from sqlglot import parse_one
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y")}).sql()
'SELECT * FROM (SELECT * FROM y) AS z /* source: x */'
>>> expand(parse_one("select * from x AS z"), {"x": parse_one("select * from y"), "y": parse_one("select * from z")}).sql()
'SELECT * FROM (SELECT * FROM (SELECT * FROM z) AS y /* source: y */) AS z /* source: x */'
Arguments:
  • expression: The expression to expand.
  • sources: A dictionary of name to Subqueryables.
  • copy: Whether or not to copy the expression during transformation. Defaults to True.
Returns:

The transformed expression.

def func( name: str, *args, dialect: Union[str, sqlglot.dialects.dialect.Dialect, Type[sqlglot.dialects.dialect.Dialect], NoneType] = None, **kwargs) -> sqlglot.expressions.Func:
5832def func(name: str, *args, dialect: DialectType = None, **kwargs) -> Func:
5833    """
5834    Returns a Func expression.
5835
5836    Examples:
5837        >>> func("abs", 5).sql()
5838        'ABS(5)'
5839
5840        >>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
5841        'CAST(5 AS DOUBLE)'
5842
5843    Args:
5844        name: the name of the function to build.
5845        args: the args used to instantiate the function of interest.
5846        dialect: the source dialect.
5847        kwargs: the kwargs used to instantiate the function of interest.
5848
5849    Note:
5850        The arguments `args` and `kwargs` are mutually exclusive.
5851
5852    Returns:
5853        An instance of the function of interest, or an anonymous function, if `name` doesn't
5854        correspond to an existing `sqlglot.expressions.Func` class.
5855    """
5856    if args and kwargs:
5857        raise ValueError("Can't use both args and kwargs to instantiate a function.")
5858
5859    from sqlglot.dialects.dialect import Dialect
5860
5861    converted: t.List[Expression] = [maybe_parse(arg, dialect=dialect) for arg in args]
5862    kwargs = {key: maybe_parse(value, dialect=dialect) for key, value in kwargs.items()}
5863
5864    parser = Dialect.get_or_raise(dialect)().parser()
5865    from_args_list = parser.FUNCTIONS.get(name.upper())
5866
5867    if from_args_list:
5868        function = from_args_list(converted) if converted else from_args_list.__self__(**kwargs)  # type: ignore
5869    else:
5870        kwargs = kwargs or {"expressions": converted}
5871        function = Anonymous(this=name, **kwargs)
5872
5873    for error_message in function.error_messages(converted):
5874        raise ValueError(error_message)
5875
5876    return function

Returns a Func expression.

Examples:
>>> func("abs", 5).sql()
'ABS(5)'
>>> func("cast", this=5, to=DataType.build("DOUBLE")).sql()
'CAST(5 AS DOUBLE)'
Arguments:
  • name: the name of the function to build.
  • args: the args used to instantiate the function of interest.
  • dialect: the source dialect.
  • kwargs: the kwargs used to instantiate the function of interest.
Note:

The arguments args and kwargs are mutually exclusive.

Returns:

An instance of the function of interest, or an anonymous function, if name doesn't correspond to an existing sqlglot.expressions.Func class.

def true() -> sqlglot.expressions.Boolean:
5879def true() -> Boolean:
5880    """
5881    Returns a true Boolean expression.
5882    """
5883    return Boolean(this=True)

Returns a true Boolean expression.

def false() -> sqlglot.expressions.Boolean:
5886def false() -> Boolean:
5887    """
5888    Returns a false Boolean expression.
5889    """
5890    return Boolean(this=False)

Returns a false Boolean expression.

def null() -> sqlglot.expressions.Null:
5893def null() -> Null:
5894    """
5895    Returns a Null expression.
5896    """
5897    return Null()

Returns a Null expression.

TRUE = (BOOLEAN this: True)
FALSE = (BOOLEAN this: False)
NULL = (NULL )